﻿using Bandit.Helpers;
using Bandit.UI;
using Bandit.UI.MVVM;
using ETC.DLEDLightingSystemPlus.Core;
using ETC.DLEDLightingSystemPlus.Helpers;
using ETC.DLEDLightingSystemPlus.Models;
using NPOI.OpenXmlFormats.Spreadsheet;
//using NPOI.SS.Formula.Udf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using static NPOI.HSSF.Util.HSSFColor;

namespace ETC.DLEDLightingSystemPlus.Windows
{
    /// <summary>
    /// FrmManage.xaml 的交互逻辑
    /// </summary>
    public partial class FrmConfig : BanditWindow
    {
        /// <summary>
        /// 视图模型
        /// </summary>
        private ViewModels.TestConfigViewModel ViewModel { get { return App.TestConfigViewModel; } }

        private TestStation _TestStation;

        private bool _IsCanEdit = false;

        private bool _IsSetModelReady = false;

        public FrmConfig(TestStation testStation,bool isCanEdit)
        {
            InitializeComponent();

            _IsCanEdit = isCanEdit;

            isUpdating = false;

            this.rtxtTestData.Document.Blocks.Clear();

            _TestStation = testStation;

            this.Loaded += delegate
            {
                this.ViewModel.OnClick = new Bandit.UI.MVVM.CommandHandler(OnClick);

                this.DataContext = ViewModel;

                _IsSetModelReady = false;

            };

            if (testStation.ConfigInfo != null)
            {
                if (testStation.ConfigInfo.TestConfig != null)
                {

                    ViewModel.ConfigInfo = testStation.ConfigInfo.Clone();

                    this.UpdateTitle();

                    //dgCfgTestItems.ItemsSource = null;
                    //dgCfgTestItems.ItemsSource = ViewModel.ConfigInfo.TestConfig.TestItems;

                    dataGridRootDiyLedModelName.ItemsSource = null;
                    dataGridRootDiyLedModelName.ItemsSource = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList;

                    if (ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList.Count > 0)
                    {
                        RootDIYLedModel rootDIYLedModel = new RootDIYLedModel();
                        rootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList[0];

                        ViewModel.TempDiyLEDCols = rootDIYLedModel.DiyLEDCols;
                        ViewModel.TempDiyLEDRows = rootDIYLedModel.DiyLEDRows;
                        ViewModel.TempLedModelList = rootDIYLedModel.DiyLedModelList;

                        RootDIYLEDItemsControls.Items.Refresh();
                    }
                    else
                    {
                        ViewModel.TempDiyLEDCols = 0;
                        ViewModel.TempDiyLEDRows = 0;
                        ViewModel.TempLedModelList = new ObservableCollection<DIYLedModel>();

                       
                        RootDIYLEDItemsControls.Items.Refresh();
                    }

                    dataGridRootQiPanLedModelName.ItemsSource = null;
                    dataGridRootQiPanLedModelName.ItemsSource = ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList;

                    if (ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList.Count > 0)
                    {
                        RootDIYLedModel rootDIYLedModel = new RootDIYLedModel();
                        rootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList[0];

                        ViewModel.TempDiyQiPanLEDCols = rootDIYLedModel.DiyLEDCols;
                        ViewModel.TempDiyQiPanLEDRows = rootDIYLedModel.DiyLEDRows;
                        ViewModel.TempQiPanLedModelList = rootDIYLedModel.DiyLedModelList;

                        RootQiPanLEDItemsControls.Items.Refresh();
                    }
                    else
                    {
                        ViewModel.TempDiyQiPanLEDCols = 0;
                        ViewModel.TempDiyQiPanLEDRows = 0;
                        ViewModel.TempQiPanLedModelList = new ObservableCollection<DIYLedModel>();

                        RootQiPanLEDItemsControls.Items.Refresh();
                    }
                }
                else
                {
                    ViewModel.ConfigInfo.TestConfig = new Core.TestConfig();

                    ViewModel.ConfigInfo.TestConfig.InitTestConfig();

                    this.UpdateTitle();

                    OnClick("RefreshLedInfo");

                    if (ViewModel.ConfigInfo.TestConfig != null)
                    {
                        if (ViewModel.ConfigInfo.TestConfig.DiyLedModelList != null && ViewModel.ConfigInfo.TestConfig.DiyLedModelList.Count > 0)
                        {

                        }
                        else
                        {

                            cbCaseCode.SelectedIndex = 0;
                            cbExeclLedInfo.SelectedIndex = 0;

                        }
                    }

                }

                //this.RefreshTestConfig();
            }

            this.Closed += (sender, e) =>
            {
                // 当窗口关闭后马上结束消息循环
                // System.Windows.Threading.Dispatcher.ExitAllFrames();
            };

        }

        #region UI Click Event

        private void OnClick(object parameter)
        {
            switch (parameter.ToString())
            {
                case "Close":
                    {
                        this.Close();
                    }
                    break;
                case "SaveSetting":
                    {
                        if (SaveConfig())
                        {

                            //Core.TestConfig.SaveConfig();

                            this.ShowDialog(App.GetString("SaveSuccess"), App.GetString("Prompt"), MessageBoxButton.OK, Bandit.UI.DialogIcon.OK);

                            this.Close();

                        }
                        else
                        {
                            this.ShowDialog(App.GetString("SaveFail"), App.GetString("Prompt"), MessageBoxButton.OK, Bandit.UI.DialogIcon.Error);

                        }
                    }
                    break;
                case "OpenAddNewDIYLedDialog":
                    {
                        #region 打开要新增的DIY LED视图
                        //if (TestConfig.Instance.RootDiyLedModelList.Count > 0)
                        //{
                        //    RootDIYLedModel rootDIYLedModel = TestConfig.Instance.RootDiyLedModelList[0];

                        //    if (rootDIYLedModel.DiyLEDCols != TestConfig.Instance.DiyLEDCols || rootDIYLedModel.DiyLEDRows != TestConfig.Instance.DiyLEDRows)
                        //    {
                        //        this.ShowDialog("请重新选择LED模板或删除所有原来的DIY LED", "错误提示", MessageBoxButton.OK, DialogIcon.Error);
                        //        break;
                        //    }
                        //}
                        tbRootName.Text = "";

                        gridNewDIYLEDName.Visibility = Visibility.Visible;

                        ViewModel.NewDiyLEDCols = ViewModel.ConfigInfo.TestConfig.DiyLEDCols; 
                        ViewModel.NewDiyLEDRows = ViewModel.ConfigInfo.TestConfig.DiyLEDRows;

                        ViewModel.NewLedModelList = new ObservableCollection<DIYLedModel>();

                        if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4)
                        {
                            foreach (var model in ViewModel.ConfigInfo.TestConfig.DiyLedModelList)
                            {

                                ViewModel.NewLedModelList.Add(new DIYLedModel()
                                {
                                    Name = model.Name,
                                    Position = model.Position,
                                    ICID = model.ICID,
                                    LEDID = model.LEDID,
                                    IsFlag = model.IsFlag,
                                    LedType = model.LedType,
                                    LightValue = model.LightValue
                                });

                            }

                        }
                        else
                        {
                            foreach (var model in ViewModel.ConfigInfo.TestConfig.DiyLedModelList)
                            {

                                ViewModel.NewLedModelList.Add(new DIYLedModel()
                                {
                                    Name = model.Name,
                                    Position = model.Position,
                                    ICID = model.ICID,
                                    LEDID = model.LEDID,
                                    IsFlag = model.IsFlag,
                                    LedType = model.LedType,
                                    LightValue = 128
                                });

                            }

                        }

                        NewRootDIYLEDItemsControls.ItemsSource = null;
                        NewRootDIYLEDItemsControls.ItemsSource = ViewModel.NewLedModelList;

                        #endregion
                    }
                    break;
                case "CloseAddDIYLEDModel":
                    {
                        gridNewDIYLEDName.Visibility = Visibility.Collapsed;
                    }
                    break;
                case "NewAddDIYLEDModel":
                    {
                        if (tbRootName.Text != "")
                        {
                            string saveDir = string.Format(@"{0}DIYImages\{1}\", this.GetBaseDirectory(), ViewModel.ConfigInfo.TestConfig.Project);
                            if (!System.IO.Directory.Exists(saveDir))
                            {
                                System.IO.Directory.CreateDirectory(saveDir);
                            }
                            //string saveFilePath = saveDir + tbRootName.Text + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".png";

                            //保存自定义pattern截图
                            //this.SaveToImage(NewRootDIYLEDItemsControls, saveFilePath, 1400, 600);

                            RootDIYLedModel rootDIYLedModel = new RootDIYLedModel();

                            rootDIYLedModel.RootName = tbRootName.Text;
                            rootDIYLedModel.DiyLEDRows = ViewModel.NewDiyLEDRows;
                            rootDIYLedModel.DiyLEDCols = ViewModel.NewDiyLEDCols;
                            //rootDIYLedModel.PathName = saveFilePath;

                            rootDIYLedModel.DiyLedModelList = ViewModel.NewLedModelList;

                            #region 对新增的DIYPattern 画面进行单独保存，方便下次直接导入

                            //TestCodeModel testCodeModel = ViewModel.ConfigInfo.TestConfig.TestCodeModels.First(s => s.TestModelCode == (int)ViewModel.ConfigInfo.TestConfig.TestModelCode);
                            string LEDInfoStr = System.IO.Path.GetFileNameWithoutExtension(ViewModel.ConfigInfo.TestConfig.xlsName);


                            string xmlDIYLEDModelPath = saveDir + tbRootName.Text + "_" + LEDInfoStr + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".xml";

                            rootDIYLedModel.xmlPathName = System.IO.Path.GetFileName(xmlDIYLEDModelPath);

                            ConfigHelper.XmlFileSerialize<RootDIYLedModel>(rootDIYLedModel, xmlDIYLEDModelPath);

                            #endregion

                            ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList.Add(rootDIYLedModel);

                            gridNewDIYLEDName.Visibility = Visibility.Collapsed;

                            dataGridRootDiyLedModelName.ItemsSource = null;
                            dataGridRootDiyLedModelName.ItemsSource = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList;

                        }
                        else
                        {
                            this.ShowDialog("请填写名称", "异常提示", MessageBoxButton.OK, DialogIcon.Error);
                        }
                    }
                    break;
                case "AddSelectDIYLEDModel":
                    {
                        Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
                        ofd.InitialDirectory = System.IO.Path.Combine(this.GetBaseDirectory(), "DIYImages");
                        ofd.Filter = "Config|*" + ".xml";
                        if (ofd.ShowDialog().Value)
                        {
                            try
                            {
                                RootDIYLedModel rootDIYLedModel = ConfigHelper.XmlFileDeserialize<RootDIYLedModel>(ofd.FileName);


                                if (rootDIYLedModel != null && rootDIYLedModel.DiyLEDCols == ViewModel.ConfigInfo.TestConfig.DiyLEDCols && rootDIYLedModel.DiyLEDRows == ViewModel.ConfigInfo.TestConfig.DiyLEDRows)
                                {

                                    rootDIYLedModel.xmlPathName = System.IO.Path.GetFileName(ofd.FileName);
                                    ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList.Add(rootDIYLedModel);

                                    //int temp = ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue;

                                    //ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = 1000;

                                    ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue;

                                    dataGridRootDiyLedModelName.ItemsSource = null;
                                    dataGridRootDiyLedModelName.ItemsSource = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList;

                                    
                                }
                                else
                                {
                                    this.ShowDialog("请选择型号一样的配置文件", "异常提示", MessageBoxButton.OK, DialogIcon.Error);
                                }
                            }
                            catch (Exception ex)
                            {
                                this.ShowDialog("选择配置文件有误，请重试", "异常提示", MessageBoxButton.OK, DialogIcon.Error);
                            }
                        }
                    }
                    break;
                case "AddSelectQiPanLEDModel":
                    {
                        Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
                        ofd.InitialDirectory = System.IO.Path.Combine(this.GetBaseDirectory(), "DIYImages");
                        ofd.Filter = "Config|*" + ".xml";
                        if (ofd.ShowDialog().Value)
                        {
                            try
                            {
                                RootDIYLedModel rootDIYLedModel = ConfigHelper.XmlFileDeserialize<RootDIYLedModel>(ofd.FileName);

                                if (rootDIYLedModel != null && rootDIYLedModel.DiyLEDCols == ViewModel.ConfigInfo.TestConfig.DiyLEDCols && rootDIYLedModel.DiyLEDRows == ViewModel.ConfigInfo.TestConfig.DiyLEDRows)
                                {

                                    

                                    ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList.Add(rootDIYLedModel);

                                    //int temp = ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue;

                                    //ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = 1000;

                                    ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue;

                                    dataGridRootQiPanLedModelName.ItemsSource = null;
                                    dataGridRootQiPanLedModelName.ItemsSource = ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList;
                                }
                                else
                                {
                                    this.ShowDialog("请选择型号一样的配置文件", "异常提示", MessageBoxButton.OK, DialogIcon.Error);
                                }
                            }
                            catch (Exception ex)
                            {
                                this.ShowDialog("选择配置文件有误，请重试", "异常提示", MessageBoxButton.OK, DialogIcon.Error);
                            }
                        }
                    }
                    break;
                case "ImportConfig":
                    {
                        ImportConfig();
                    }
                    break;
                case "EditLightOk":
                    {
                        EditLightOk();
                    }
                    break;
                case "CloseSetLEDLightucPannel":
                    {
                        this.SetLedLightGrid.Visibility = Visibility.Collapsed;
                    }
                    break;
                case "CloseSetTempLEDLightucPannel":
                    {
                        this.SetTempLedLightGrid.Visibility = Visibility.Collapsed;
                    }
                    break;
                case "EditTempLightOk":
                    {
                        TempEditLightOk();
                    }
                    break;
                case "RefreshLedInfo":
                    {
                        //LogInfoExcelMode logInfoExcelMode = ViewModel.xlsNames.First(s => s.ExcelPath == (string)comboBox.SelectedValue);

                        //string LedInfoPath = this.GetBaseDirectory() + "LEDTemplateFiles\\" + logInfoExcelMode.ExcelPath.Trim();//+ this.cbExeclLedInfo.SelectedValue.ToString();
                        string LedInfoPath = this.GetBaseDirectory() + "LEDTemplateFiles\\" + ViewModel.ConfigInfo.TestConfig.xlsName;

                        if (File.Exists(LedInfoPath))
                        {

                            LoadICLEDForExeclNPOI(LedInfoPath);

                        }
                        else
                        {
                            ViewModel.ConfigInfo.TestConfig.DiyLedModelList = new ObservableCollection<DIYLedModel>();

                            ViewModel.ConfigInfo.TestConfig.DiyLEDRows = 0;
                            ViewModel.ConfigInfo.TestConfig.DiyLEDCols = 0;

                            LeftItemsControls.ItemsSource = null;
                            LeftItemsControls.ItemsSource = ViewModel.ConfigInfo.TestConfig.DiyLedModelList;
                        }

                        ComparerTestItemCurrentValue();
                    }
                    break;
                //case "SingleSetMode":
                //    {
                //        SingleSetMode();
                //    }
                //    break;
                case "ClosePower":
                    {
                        Task.Factory.StartNew(() =>
                        {
                            this.Loading.Show("PowerOff...");
                            _TestStation.DLEDLightingHelper.PowerOff();
                        }).ContinueWith(t =>
                        {
                            this.Loading.Hide();
                        });
                    }
                    break;
                case "SetCurrentLimit":
                    {
                        string pwd = "TPKETC";//+ DateTime.Now.ToString("yyyyMMdd");
#if DEBUG

                        pwd = "";

#endif
                        if(this.ShowPasswordDialog("Engineer Login", pwd))
                        {
                            this.SetCurrentLimitGridName.Visibility = Visibility.Visible;
                        }
                        else
                        {
                            this.ShowPromptWindow("输入密码错误", PromptType.Red, 3);
                        }

                    }
                    break;
                case "OKSetCurrentUpper":
                    {
                        this.SetCurrentLimitGridName.Visibility = Visibility.Collapsed;

                        this.Loading.Show("Refresh...");

                        Task.Factory.StartNew(new Action(() =>
                        {
                            ComparerTestItemCurrentValue();

                        })).ContinueWith(t =>
                        {
                            this.Loading.Hide();
                        });
                        
                    }
                    break;
                default:
                    if (parameter.ToString().StartsWith("Pattern"))
                    {
                        GenerateCommonPattern(parameter.ToString());
                    }
                    break;
            }
        }


        #endregion

        #region 生成一些常用Pattern
        /// <summary>
        /// 生成一些常用Pattern
        /// AddByBandit - 2024年8月26日 20:36:43
        /// </summary>
        /// <param name="name"></param>
        private void GenerateCommonPattern(string name)
        {
            double reaLightCurrentValue = Math.Round(this.CompareReaCurrent(ViewModel.NewLightValue), 5);
            if (reaLightCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
            {
                this.ShowPromptWindow(string.Format("设置电流值:{0}大于上限值，上限值为[{1}]", reaLightCurrentValue, ViewModel.ConfigInfo.TestConfig.CurrentUpper), PromptType.Red);
                IsCtrlKeyDown = false;
                return;
            }

            switch (name)
            {
                //增加棋盘格快速生成设置 - AddByBandit - 2024年8月26日 17:21:56
                case "PatternChecker":
                case "PatternCheckerReverse":
                    {
                        foreach (var item in ViewModel.NewLedModelList)
                        {
                            bool flag = (item.Position.X + item.Position.Y) % 2 != 0; //(item.Position.X % 2 == 0 && item.Position.Y % 2 != 0) || (item.Position.X % 2 != 0 && item.Position.Y % 2 == 0);

                            if (name.EndsWith("Reverse"))
                            {
                                flag = !flag;
                            }

                            if (flag)
                            {
                                item.LedType = "Nomal";
                                item.LightValue = ViewModel.NewLightValue;
                                item.ReaLightCurrentValue = reaLightCurrentValue;//Math.Round(this.CompareReaCurrent(dIYLedModel.LightValue), 5);
                            }
                            else
                            {
                                item.LedType = "Idle";

                                if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 6 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 7)
                                {

                                    item.LightValue = 0;
                                    item.ReaLightCurrentValue = this.CompareReaCurrent(item.LightValue);
                                }
                                else
                                {
                                    item.LightValue = 128;
                                    item.ReaLightCurrentValue = 0;
                                }
                            }
                        }
                    }
                    break;
                case "PatternMosaic1":
                case "PatternMosaic2":
                    {
                        int rowHalf = ViewModel.ConfigInfo.TestConfig.DiyLEDRows / 2;

                        foreach (var item in ViewModel.NewLedModelList)
                        {
                            bool flag = false;
                            if (item.Position.X <= rowHalf)
                            {
                                flag = item.Position.Y % 2 == 0;
                            }
                            else
                            {
                                flag = item.Position.Y % 2 != 0;
                            }

                            if (name.EndsWith("2"))
                            {
                                flag = !flag;
                            }

                            if (flag)
                            {
                                item.LedType = "Nomal";
                                item.LightValue = ViewModel.NewLightValue;
                                item.ReaLightCurrentValue = reaLightCurrentValue;//Math.Round(this.CompareReaCurrent(dIYLedModel.LightValue), 5);
                            }
                            else
                            {
                                item.LedType = "Idle";
                                if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 6 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 7)
                                {

                                    item.LightValue = 0;
                                    item.ReaLightCurrentValue = this.CompareReaCurrent(item.LightValue);
                                }
                                else
                                {
                                    item.LightValue = 128;
                                    item.ReaLightCurrentValue = 0;
                                }
                            }
                        }
                    }
                    break;
                case "PatternMosaic3":
                case "PatternMosaic4":
                    {
                        int colHalf = ViewModel.ConfigInfo.TestConfig.DiyLEDCols / 2;

                        foreach (var item in ViewModel.NewLedModelList)
                        {
                            bool flag = false;
                            if (item.Position.Y <= colHalf)
                            {
                                flag = item.Position.X % 2 == 0;
                            }
                            else
                            {
                                flag = item.Position.X % 2 != 0;
                            }

                            if (name.EndsWith("4"))
                            {
                                flag = !flag;
                            }

                            if (flag)
                            {
                                item.LedType = "Nomal";
                                item.LightValue = ViewModel.NewLightValue;
                                item.ReaLightCurrentValue = reaLightCurrentValue;//Math.Round(this.CompareReaCurrent(dIYLedModel.LightValue), 5);
                            }
                            else
                            {
                                item.LedType = "Idle";
                                item.LightValue = 0;
                                item.ReaLightCurrentValue = this.CompareReaCurrent(item.LightValue);
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        #endregion

        #region 导入现有配置
        private void ImportConfig()
        {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            //ofd.InitialDirectory = System.IO.Path.Combine(this.GetBaseDirectory(), "Configs");
            ofd.Filter = "Config|*" + App.TestConfigFileExtension;
            if (ofd.ShowDialog().Value)
            {
                try
                {
                    //string dir = App.GetPathOfConfig();
                    //string[] arr = System.IO.Directory.GetFiles(dir, System.IO.Path.GetFileName(ofd.FileName));
                    //if (arr.Length == 0)
                    //{

                    //}

                    //byte number = ViewModel.ConfigInfo.TestConfig.ProductNumber;

                    this.Loading.Show("Loading...");

                    Task.Factory.StartNew(() =>
                    {
                        ViewModel.ConfigInfo.TestConfig = Bandit.Helpers.ConfigHelper.XmlFileDeserialize<TestConfig>(ofd.FileName);

                    }).ContinueWith(t =>
                    {
                        this.Dispatcher.Invoke(new Action(() =>
                        {
                            this.UpdateTitle();

                            dataGridRootDiyLedModelName.ItemsSource = null;
                            dataGridRootDiyLedModelName.ItemsSource = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList;

                            LeftItemsControls.ItemsSource = null;
                            LeftItemsControls.ItemsSource = ViewModel.ConfigInfo.TestConfig.DiyLedModelList;

                            if (ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList.Count > 0)
                            {
                                RootDIYLedModel rootDIYLedModel = new RootDIYLedModel();
                                rootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList[0];

                                ViewModel.TempDiyLEDCols = rootDIYLedModel.DiyLEDCols;
                                ViewModel.TempDiyLEDRows = rootDIYLedModel.DiyLEDRows;
                                ViewModel.TempLedModelList = rootDIYLedModel.DiyLedModelList;

                                RootDIYLEDItemsControls.ItemsSource = null;
                                RootDIYLEDItemsControls.ItemsSource = ViewModel.TempLedModelList;

                                RootDIYLEDItemsControls.Items.Refresh();
                            }
                            else
                            {
                                ViewModel.TempDiyLEDCols = 0;
                                ViewModel.TempDiyLEDRows = 0;
                                ViewModel.TempLedModelList = new ObservableCollection<DIYLedModel>();

                                RootDIYLEDItemsControls.ItemsSource = null;
                                RootDIYLEDItemsControls.ItemsSource = ViewModel.TempLedModelList;

                                RootDIYLEDItemsControls.Items.Refresh();
                            }

                            dataGridRootQiPanLedModelName.ItemsSource = null;
                            dataGridRootQiPanLedModelName.ItemsSource = ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList;

                            if (ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList.Count > 0)
                            {
                                RootDIYLedModel rootDIYLedModel = new RootDIYLedModel();
                                rootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList[0];

                                ViewModel.TempDiyQiPanLEDCols = rootDIYLedModel.DiyLEDCols;
                                ViewModel.TempDiyQiPanLEDRows = rootDIYLedModel.DiyLEDRows;
                                ViewModel.TempQiPanLedModelList = rootDIYLedModel.DiyLedModelList;

                                RootQiPanLEDItemsControls.ItemsSource = null;
                                RootQiPanLEDItemsControls.ItemsSource = ViewModel.TempQiPanLedModelList;

                                RootQiPanLEDItemsControls.Items.Refresh();
                            }
                            else
                            {
                                ViewModel.TempDiyQiPanLEDCols = 0;
                                ViewModel.TempDiyQiPanLEDRows = 0;
                                ViewModel.TempQiPanLedModelList = new ObservableCollection<DIYLedModel>();

                                RootQiPanLEDItemsControls.ItemsSource = null;
                                RootQiPanLEDItemsControls.ItemsSource = ViewModel.TempQiPanLedModelList;

                                RootQiPanLEDItemsControls.Items.Refresh();
                            }
                        }));

                        this.Loading.Hide();
                        //this.RefreshTestConfig();

                    });



                }
                catch (Exception ex)
                {
                    Bandit.Helpers.LogHelper.Error(ex, "ImportConfig");
                    this.ShowDialog(string.Format("[Err] {0}", ex.Message), App.PromptText, MessageBoxButton.OK, DialogIcon.Error);
                }
            }
        }
        #endregion

        #region 更新标题
        private void UpdateTitle()
        {
            string configName = System.IO.Path.GetFileName(ViewModel.ConfigInfo.TestConfig.FileName);

            if (string.IsNullOrWhiteSpace(configName))
            {
                configName = "New Config";
            }

            this.Title = string.Format("Test Config - {0}", configName);
        }
        #endregion

        #region 保存配置
        private bool SaveConfig()
        {
            foreach(TestItem testItem in ViewModel.ConfigInfo.TestConfig.TestItems)
            {
                if(testItem != null)
                {
                    if(testItem.IsRealityCurrentValueLimit != null)
                    {
                        if (testItem.IsReaValue)
                        {
                            if (testItem.IsRealityCurrentValueLimit == "false")
                            {
                                this.ShowDialog("测试项目设置值过大，请重新填写", "提示", MessageBoxButton.OK, DialogIcon.Error);
                                return false;
                            }
                        }
                    }
                    if (testItem.IsLimit)
                    {
                        if(testItem.Limit.Upper <= testItem.Limit.Lower)
                        {
                            this.ShowDialog(string.Format("{0}测试项目下限值大于下限值，请重新填写",testItem.Name), "提示", MessageBoxButton.OK, DialogIcon.Error);
                            return false;
                        }
                    }
                }
                else
                {
                    return false;
                }
            }

            string fileName = _TestStation.StationInfo.TestConfigFile;

            if (string.IsNullOrWhiteSpace(fileName) || System.IO.Path.GetExtension(fileName).ToLower() == ".xml")
            {
                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

                sfd.InitialDirectory = App.GetPathOfConfig();
                sfd.FileName = ViewModel.ConfigInfo.TestConfig.ConfigName;
                sfd.Filter = "Config|*" + App.TestConfigFileExtension;
                if (sfd.ShowDialog().Value)
                {
                    fileName = sfd.FileName;

                    if (!fileName.ToLower().StartsWith(App.GetPathOfConfig().ToLower()))
                    {
                        this.ShowDialog("为保证数据完整性，请将配置保存到软件目录下的Configs文件夹里面", "警告", MessageBoxButton.YesNo, DialogIcon.Warning);
                        return false;
                    }

                    if(App.MainViewModel.TestStations.Where(s=>s.StationInfo.TestConfigFile ==System.IO.Path.GetFileName(fileName)).Count() > 0)
                    {
                        this.ShowDialog("为保证数据完整性，请将配置文件名设置成其它名称", "警告", MessageBoxButton.YesNo, DialogIcon.Warning);
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                fileName = this.GetBaseDirectory() + "Configs\\" + fileName;
            }

            if (!StorageConfig(fileName))
            {
                return false;
            }

            this.UpdateTitle();

            return true;
        }

        private bool StorageConfig(string fileName)
        {
            
            //保存配置
            ViewModel.ConfigInfo.TestConfig.SaveConfig(fileName);

            Thread.Sleep(1000);
            //复制新配置到工位
            this.Dispatcher.Invoke(new Action(()=>{

                ViewModel.ConfigInfo.CopyTo(this._TestStation.ConfigInfo);

            }));
           
            string relativePath = System.IO.Path.GetFileName(fileName);//.GetBetweenValue("Configs\\", "", true);

            if (this._TestStation.StationInfo.TestConfigFile != relativePath)
            {
                //更新站点配置文件
                this._TestStation.StationInfo.TestConfigFile = relativePath;// System.IO.Path.GetFileName(fileName);

                //保存站点信息
                App.MainViewModel.SaveStations();
            }

            return true;
        }

        #endregion

        #region Mode 选择事件 

        
        private void cbCaseCode_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           
            //if (e.Source.GetType() == typeof(TabControl))
            //{
            //    return;
            //}

            ComboBox comboBox = sender as ComboBox;

            if (comboBox.SelectedValue == null)
            {
                return;
            }

            //if (isUpdating)
            //    return;

            //isUpdating = true;

            Console.WriteLine("进来了");

            Console.WriteLine("Select case :" + comboBox.SelectedValue);

            TestCodeModel testCodeModel = ViewModel.ConfigInfo.TestConfig.TestCodeModels.First(s => s.TestModelCode == (int)comboBox.SelectedValue);

            Console.WriteLine("Select case name:" + testCodeModel.Name);

            if (testCodeModel.TestModelCode == 1 || testCodeModel.TestModelCode == 8 || testCodeModel.TestModelCode == 9)
            {
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetBC = false;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetMC = true;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetValue = false;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetScale = false;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetILED = false;
                ViewModel.ConfigInfo.TestConfig.IsVisilitySetPattern = true;
            }
            else if(testCodeModel.TestModelCode == 10)
            {
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetBC = false;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetMC = false;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetValue = false;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetScale = true;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetILED = true;
                ViewModel.ConfigInfo.TestConfig.IsVisilitySetPattern = true;
            }
            else if (testCodeModel.TestModelCode == 11 || testCodeModel.TestModelCode == 17 || testCodeModel.TestModelCode == 31)
            {
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetBC = false;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetMC = true;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetValue = false;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetScale = false;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetILED = false;
                ViewModel.ConfigInfo.TestConfig.IsVisilitySetPattern = true;

                AddTX037TestItem();

            }
            else
            {
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetBC = true;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetMC = true;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetValue = true;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetScale = false;
                ViewModel.ConfigInfo.TestConfig.IsDIYPictureSetILED = false;
                ViewModel.ConfigInfo.TestConfig.IsVisilitySetPattern = true;
            }

            string strDefaultValue = ConfigHelper.GetVauleToString(testCodeModel.Name + "_CMDDefaultValue");

            string[] DefaultValueArr = strDefaultValue.Split(';');

            if(DefaultValueArr.Length == 19)
            {
                ViewModel.ConfigInfo.TestConfig.DvledValue =    double.Parse(DefaultValueArr[0].Trim() == "" ? "1" : DefaultValueArr[0]);
                ViewModel.ConfigInfo.TestConfig.DvLedOvpValue = double.Parse(DefaultValueArr[1].Trim() == "" ? "1" : DefaultValueArr[1]);
                ViewModel.ConfigInfo.TestConfig.DvLedOcpValue = double.Parse(DefaultValueArr[2].Trim() == "" ? "1" : DefaultValueArr[2]);
                ViewModel.ConfigInfo.TestConfig.DICOvpValue =   double.Parse(DefaultValueArr[3].Trim() == "" ? "1" : DefaultValueArr[3]);
                ViewModel.ConfigInfo.TestConfig.DICOcpValue =   double.Parse(DefaultValueArr[4].Trim() == "" ? "1" : DefaultValueArr[4]);

                ViewModel.ConfigInfo.TestConfig.IsMCSet = DefaultValueArr[5].Trim() == "" ? false : true;
                ViewModel.ConfigInfo.TestConfig.IMCValue = int.Parse(DefaultValueArr[5].Trim() == "" ? "1" : DefaultValueArr[5]);

                ViewModel.ConfigInfo.TestConfig.IsDCSet = DefaultValueArr[6].Trim() == "" ? false : true;
                ViewModel.ConfigInfo.TestConfig.IsBCSet = DefaultValueArr[7].Trim() == "" ? false : true;

                ViewModel.ConfigInfo.TestConfig.IDCValue = int.Parse(DefaultValueArr[6].Trim() == "" ? "1" : DefaultValueArr[6]);
                ViewModel.ConfigInfo.TestConfig.IBCValue = int.Parse(DefaultValueArr[7].Trim() == "" ? "1" : DefaultValueArr[7]);

                ViewModel.ConfigInfo.TestConfig.IsScaleSet = DefaultValueArr[8].Trim() == "" ? false : true;
                ViewModel.ConfigInfo.TestConfig.IsSRCSet = DefaultValueArr[9].Trim() == "" ? false : true;
                ViewModel.ConfigInfo.TestConfig.IsLEDNUMSet = DefaultValueArr[10].Trim() == "" ? false : true;
                ViewModel.ConfigInfo.TestConfig.IsRSETSet = DefaultValueArr[11].Trim() == "" ? false : true;
                ViewModel.ConfigInfo.TestConfig.IsCLKSet = DefaultValueArr[12].Trim() == "" ? false : true;

                ViewModel.ConfigInfo.TestConfig.IScaleValue = int.Parse(DefaultValueArr[8].Trim() == "" ? "1" : DefaultValueArr[8]);
                ViewModel.ConfigInfo.TestConfig.ISrcValue = int.Parse(DefaultValueArr[9].Trim() == "" ? "1" : DefaultValueArr[9]);
                ViewModel.ConfigInfo.TestConfig.ILEDNUMValue = int.Parse(DefaultValueArr[10].Trim() == "" ? "1" : DefaultValueArr[10]);
                ViewModel.ConfigInfo.TestConfig.IRSETValue = int.Parse(DefaultValueArr[11].Trim() == "" ? "1" : DefaultValueArr[11]);
                ViewModel.ConfigInfo.TestConfig.ICLKValue = int.Parse(DefaultValueArr[12].Trim() == "" ? "1" : DefaultValueArr[12]);


                ViewModel.ConfigInfo.TestConfig.IsPwmModeSet = DefaultValueArr[13].Trim() == "" ? false : true;
                ViewModel.ConfigInfo.TestConfig.PwnModeCode = int.Parse(DefaultValueArr[13].Trim() == "" ? "1" : DefaultValueArr[13]);

                ViewModel.ConfigInfo.TestConfig.IsILEDSet = DefaultValueArr[14].Trim() == "" ? false : true;
                ViewModel.ConfigInfo.TestConfig.IILEDValue = int.Parse(DefaultValueArr[14].Trim() == "" ? "1" : DefaultValueArr[14]);

                ViewModel.ConfigInfo.TestConfig.ICCount = int.Parse(DefaultValueArr[15].Trim() == "" ? "1" : DefaultValueArr[15]);
                ViewModel.ConfigInfo.TestConfig.LEDCount = int.Parse(DefaultValueArr[16].Trim() == "" ? "1" : DefaultValueArr[16]);
                ViewModel.ConfigInfo.TestConfig.IC_PinCount = int.Parse(DefaultValueArr[17].Trim() == "" ? "1" : DefaultValueArr[17]);

                ViewModel.ConfigInfo.TestConfig.TestCaseType = int.Parse(DefaultValueArr[18].Trim() == "" ? "1" : DefaultValueArr[18]);

            }

            foreach (TestItem testItem in ViewModel.ConfigInfo.TestConfig.TestItems)
            {
                TestItemDefaults testItemDefaults = App.TestItemDefaultRoot.TestItemDefaults.Find(s => s.name == testCodeModel.Name);

                bool IsTest = testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).IsTest == "1" ? true : false;

                testItem.IsTest = IsTest;

                testItem.IsSetMcValue = testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).IsMCSet == "1" ? true : false;

                testItem.SetMcValue = int.Parse(testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).SetMC);

                testItem.IsSetDcValue = testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).IsDCSet == "1" ? true : false;

                testItem.SetDcValue = int.Parse(testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).SetDC);

                testItem.IsSetBcValue = testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).IsBCSet == "1" ? true : false;

                testItem.SetBcValue = int.Parse(testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).SetBC);

                testItem.IsSetCurrentValue = testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).IsCurrentSet == "1" ? true : false;

                testItem.SetCurrentValue = double.Parse(testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).SetCurrent);

                testItem.DelayTime = int.Parse(testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).Delay);

                testItem.Limit.Upper = double.Parse(testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).Upper);

                testItem.Limit.Lower = double.Parse(testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).Lower);

                testItem.IsReaValue = testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).IsReaValue == "1" ? true : false;

                testItem.IsSetScaleValue = testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).IsSCALESet == "1" ? true : false;

                testItem.SetScaleValue = int.Parse(testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).SetSCALE);

                testItem.IsSetILedValue = testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).IsILEDSet == "1" ? true : false;

                testItem.SetILedValue = int.Parse(testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).SetILED);

                testItem.IsSetCompensationValue = testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).IsSetCompensation == "1" ? true : false;

                testItem.SetCompensationValue = double.Parse(testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).SetCompensationValue);

                if (ViewModel.ConfigInfo.TestConfig.Station == "AOI#1" || ViewModel.ConfigInfo.TestConfig.Station == "AOI#2")
                {
                    if (!(testItem.TestItemCode == "FullScreenLowCurrent" || testItem.TestItemCode == "PINShortOpenTest"))
                        testItem.IsTest = false;

                }
                if (ViewModel.ConfigInfo.TestConfig.Station == "AC#1" || ViewModel.ConfigInfo.TestConfig.Station == "AC#2")
                {
                    if (!(testItem.TestItemCode == "FullScreenHighCurrent" || testItem.TestItemCode == "PINShortOpenTest"))
                        testItem.IsTest = false;

                }
               
            }

            // TestCodeCurrentUpperModel testCodeCurrentUpperModel = ViewModel.ConfigInfo.TestConfig.TestCodeCurrentUpperModels.First(s => s.TestModelCode == (int)comboBox.SelectedValue);
            TestCodeCurrentUpperModel testCodeCurrentUpperModel = ViewModel.ConfigInfo.TestConfig.TestCodeCurrentUpperModels.First(s => s.TestModelCode == testCodeModel.TestModelCode);
            ViewModel.ConfigInfo.TestConfig.CurrentUpper = testCodeCurrentUpperModel.CurrentUpper;

            ComparerTestItemCurrentValue();

            //isUpdating = false;
        }

        #region TX037TestItem
        public void AddTX037TestItem()
        {
            //TestItem(int num, string testItemCode, string name, bool isTestVisibility, bool isSetMC, int setMCValue, bool isSetDC, int setDCValue, bool isSetBC, int setBCValue,bool isSetScale,int setScaleValue,bool isSetIled,int setILEDValue, bool isSetCurrentValue, double setCurrentValue,  int delayTime, bool isLimit, Limit limit, string unit,bool isReaValue)
            //TestItem(int num, string testItemCode, string name, bool isTestVisibility, bool isSetMC, int setMCValue, bool isSetDC, int setDCValue, bool isSetBC, int setBCValue,bool isSetScale,int setScaleValue, bool isSetSRC, int setSRCValue, bool isSetIled,int setILEDValue,bool isSetGCG1,int setGCG1Value,bool isSetGCG2,int setGCG2Value,bool isSetHLMS,int setHLMSValue, bool isSetCurrentValue, double setCurrentValue,  int delayTime, bool isLimit, Limit limit, string unit,bool isReaValue)

            ViewModel.ConfigInfo.TestConfig.TestItems = new ObservableCollection<TestItem>();
            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(1, "PINShortOpenTest", "PIN短路开路测试", false, false, 0, false, 0, false, 0, false, 0,  false, 0, false, 0, 1, false, new Limit(0, 0), "", false, false, 0));
            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(2, "ChipStandbyCurrent", "芯片待机电流(mA)", false, false, 0, false, 0, false, 0, false, 0, false, 0,  false, 0, 1, true, new Limit(0, 300), "mA", false, false, 0));
            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(3, "ChipWorkingCurrent", "芯片正常运行电流(mA)", false, false, 0, false, 0, false, 0, false, 0,  false, 0,  false, 0, 1, true, new Limit(10, 300), "mA", false, false, 0));
            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(4, "CurrentTest10uA", "Open/Short测试", true, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, 1, false, new Limit(0, 0.7), "", false, false, 0));
            //this._TestItems.Add(new TestItem(7, "VScanTest", "垂直扫描", true, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 4095, 100, false, new Limit(0, 4.7), "mA", false));
            //this._TestItems.Add(new TestItem(8, "HScanTest", "水平扫描", true, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 4095, 100, false, new Limit(0, 4.7), "mA", false));

            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(5, "VLEDFullyClosedCurrent", "VLED亮度全关的漏电流(mA)", true, false, 0, false, 0, false, 0, false, 0,  false, 0, false, 0, 1, true, new Limit(0, 0.7), "mA", false, false, 0));
            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(6, "IFBDataTest", "IFB电流值测试(uA)", false, false, 0, false, 0, false, 0, false, 0,  false, 0,false, 0, 1, true, new Limit(0, 300), "uA", false, false, 0));

            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(7, "FullCurrentTest1", "全电流测试1(mA)", true, true, 2, false, 0, false, 0, false, 0,  false, 0,  true, 4095, 1, true, new Limit(0, 100.7), "mA", true, false, 0));
            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(8, "FullCurrentTest2", "全电流测试2(mA)", true, true, 3, false, 0, false, 0, false, 0,  false, 0, true, 4095, 1, true, new Limit(0, 100.7), "mA", true, false, 0));
            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(9, "FullCurrentTest3", "全电流测试3(mA)", true, true, 4, false, 0, false, 0, false, 0,  false, 0,true, 4095, 1, true, new Limit(0, 100.7), "mA", true, false, 0));
            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(10, "QiPanPattenDisplay", "棋盘格图案显示", true, false, 0, false, 0, false, 0, false, 0,  false, 0, false, 0.1, 1000, false, new Limit(0, 50), "", false, false, 0));
            ViewModel.ConfigInfo.TestConfig.TestItems.Add(new TestItem(11, "DIYPattenDisplay", "DIY图案显示", true, false, 0, false, 0, false, 0, false, 0,  false, 0, false, 0.1, 1000, false, new Limit(0, 50), "", false, false, 0));

        }

        #endregion

        #endregion

        #region 加载Excel文档
        private void cbExcelLedInfo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;

            if (comboBox.SelectedValue == null)
            {
                return;
            }

            string LedInfoPath = this.GetBaseDirectory() + "LEDTemplateFiles\\" + ViewModel.ConfigInfo.TestConfig.xlsName;

            if (File.Exists(LedInfoPath))
            {

                LoadICLEDForExeclNPOI(LedInfoPath);

            }
            else
            {
                ViewModel.ConfigInfo.TestConfig.DiyLedModelList = new ObservableCollection<DIYLedModel>();

                ViewModel.ConfigInfo.TestConfig.DiyLEDRows = 0;
                ViewModel.ConfigInfo.TestConfig.DiyLEDCols = 0;

                LeftItemsControls.ItemsSource = null;
                LeftItemsControls.ItemsSource = ViewModel.ConfigInfo.TestConfig.DiyLedModelList;
            }

            ComparerTestItemCurrentValue();

        }
        private void LoadICLEDForExeclNPOI(string execlPath)
        {
            ViewModel.ConfigInfo.TestConfig.DiyLedModelList = new ObservableCollection<DIYLedModel>();

            DataTable dataTable = ExcelToTB(execlPath, "Sheet1");

            if (dataTable == null) return;

            ViewModel.ConfigInfo.TestConfig.DiyLEDRows = dataTable.Rows.Count;
            ViewModel.ConfigInfo.TestConfig.DiyLEDCols = dataTable.Columns.Count;

            for (int row = 0; row < dataTable.Rows.Count; row++)
            {
                DataRow dataRow = dataTable.Rows[row];

                for (int col = 0; col < dataTable.Columns.Count; col++)
                {
                    string data = dataRow[col].ToString();

                    string[] strArr = data.Split("_");
                    if(strArr.Length != 2) {

                        Console.WriteLine(data);

                    }
                   // string ICStr = strArr[0].ToString();
                    string id = strArr[1].ToString();

                    DIYLedModel dIYLedModel = new DIYLedModel();

                    if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 6 && strArr.Length == 3)
                    {
                        string ICStr = strArr[0].ToString();

                        string ScanNumStr = strArr[1].ToString();

                        id = strArr[2].ToString();

                        dIYLedModel.Name = "LED_" + ScanNumStr + "_" + ICStr + "_" + id;

                        dIYLedModel.Scan_num = ScanNumStr;

                        dIYLedModel.ICID = ICStr;

                        dIYLedModel.LEDID = int.Parse(id);

                    }
                    else if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 && strArr.Length == 3)
                    {
                        string ICStr = strArr[1].ToString();

                        string ScanNumStr = strArr[0].ToString();

                        id = strArr[2].ToString();

                        dIYLedModel.Name = "LED_" + ScanNumStr + "_" + ICStr + "_" + id;

                        dIYLedModel.Scan_num = ScanNumStr;

                        dIYLedModel.ICID = ICStr;

                        dIYLedModel.LEDID = int.Parse(id);
                    }
                    else
                    {
                        string ICStr = strArr[0].ToString();

                        dIYLedModel.Name = "LED_" + ICStr + "_" + id;

                        dIYLedModel.ICID = ICStr;

                        dIYLedModel.LEDID = int.Parse(id);

                    }
                    //dIYLedModel.Name = "LED_" + ICStr + "_" + id;

                    //dIYLedModel.ICID = ICStr;
                    //dIYLedModel.LEDID = int.Parse(id);

                    dIYLedModel.Position = new Point(row, col);
                    dIYLedModel.LightValue = 0;

                    dIYLedModel.ReaLightCurrentValue = this.CompareReaCurrent(dIYLedModel.LightValue); 

                    if (id != "0")
                    {
                        dIYLedModel.IsFlag = Visibility.Visible;
                    }
                    else
                    {
                        dIYLedModel.IsFlag = Visibility.Collapsed;
                    }

                    dIYLedModel.LedType = "Idle";

                    ViewModel.ConfigInfo.TestConfig.DiyLedModelList.Add(dIYLedModel);
                }
            }

            LeftItemsControls.ItemsSource = null;
            LeftItemsControls.ItemsSource = ViewModel.ConfigInfo.TestConfig.DiyLedModelList;

        }

        #region 读取csv
        /// <summary>
        /// 读取CSV文件
        /// </summary>
        /// <param name="filePath">文件路径 eg：D:\A.csv</param>
        /// <param name="dt">数据（无标题）</param>
        /// <param name="csvTitles">标题</param>
        public DataTable ExcelToTB(string filePath, string SheetName)
        {
            try
            {
                using (ExcelHelper excelHelper = new ExcelHelper(filePath))
                {
                    return excelHelper.ExcelToDataTable(SheetName, false);//读取数据                     
                }
            }
            catch (Exception ex)
            {
                LogHelper.Info(ex.Message);
                return null;
            }
        }
        #endregion

        #endregion

        #region CbStationName_SelectionChanged

        private bool isUpdating = false;
        private void CbStationName_SelectionChanged(object sender,SelectionChangedEventArgs e)
        {
          
            ComboBox comboBox = sender as ComboBox;

            if (comboBox.SelectedValue == null)
            {
                return;
            }

            //if (isUpdating)
            //    return;

            //isUpdating = true;

            Console.WriteLine("Select case :" + comboBox.SelectedValue);

            StationModel stationModel = ViewModel.ConfigInfo.TestConfig.StationNameDic.First(s => s.StationCode == (string)comboBox.SelectedValue);

            Console.WriteLine("Select case name:" + stationModel.Name);

            string stationName = stationModel.Name;//(string)comboBox.SelectedValue;

            if (ViewModel.ConfigInfo.TestConfig != null)
            {
                foreach (TestItem testItem in ViewModel.ConfigInfo.TestConfig.TestItems)
                {
                    TestCodeModel testCodeModel = ViewModel.ConfigInfo.TestConfig.TestCodeModels.First(s => s.TestModelCode == ViewModel.ConfigInfo.TestConfig.TestModelCode);

                    TestItemDefaults testItemDefaults = App.TestItemDefaultRoot.TestItemDefaults.Find(s => s.name == testCodeModel.Name);

                    bool IsTest = testItemDefaults.TestItemConfig.Find(s => s.name == testItem.TestItemCode).IsTest == "1" ? true : false;

                    testItem.IsTest = IsTest;

                    if (stationName == "AOI#1" || stationName == "AOI#2")
                    {
                        if (!(testItem.TestItemCode == "FullScreenLowCurrent" || testItem.TestItemCode == "PINShortOpenTest" || testItem.TestItemCode == "ChipWorkingCurrent" ))
                            testItem.IsTest = false;

                    }
                    if (stationName == "AC#1" || stationName == "AC#2")
                    {
                        if (!(testItem.TestItemCode == "FullScreenHighCurrent" || testItem.TestItemCode == "PINShortOpenTest" || testItem.TestItemCode == "ChipWorkingCurrent" ))
                            testItem.IsTest = false;

                    }

                }
            }

            //isUpdating = false;
        }
        
        #endregion
        private void SaveToImage(FrameworkElement ui, string fileName, int width, int height)
        {
            try
            {
                System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
                RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d,
                PixelFormats.Pbgra32);
                bmp.Render(ui);
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                encoder.Save(fs);
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        #region Pattern 表格事件
        RootDIYLedModel CurrentSelectRootDIYLedModel = new RootDIYLedModel();
        /// <summary>
        /// 表格选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridRootDiyLedModelName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataGrid dataGrid = sender as DataGrid;

            Console.WriteLine("-----------------:" + dataGrid.SelectedIndex);

            if (dataGrid.SelectedIndex >= 0)
            {
                RootDIYLedModel rootDIYLedModel = new RootDIYLedModel();
                rootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList[dataGrid.SelectedIndex];

                CurrentSelectRootDIYLedModel = new RootDIYLedModel();
                CurrentSelectRootDIYLedModel = rootDIYLedModel;
                CurrentSelectRootDIYLedModel.xmlPathName = System.IO.Path.GetFileName(rootDIYLedModel.xmlPathName);

                ViewModel.TempDiyLEDCols = rootDIYLedModel.DiyLEDCols;
                ViewModel.TempDiyLEDRows = rootDIYLedModel.DiyLEDRows;
                ViewModel.TempLedModelList = rootDIYLedModel.DiyLedModelList;

                RootDIYLEDItemsControls.Items.Refresh();
            }
        }

        /// <summary>
        /// 删除pattern 事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteRootDiyLedButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (this.ShowDialog("确认删除？", "确定", MessageBoxButton.OKCancel, DialogIcon.Question) == MessageBoxResult.OK)
            {

                DataGrid dataGrid = dataGridRootDiyLedModelName;

                Console.WriteLine("-----------------:" + dataGrid.SelectedIndex);

                ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList.RemoveRange(dataGrid.SelectedIndex, 1);

                dataGridRootDiyLedModelName.ItemsSource = null;
                dataGridRootDiyLedModelName.ItemsSource = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList;

                if (ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList.Count > 0)
                {
                    RootDIYLedModel rootDIYLedModel = new RootDIYLedModel();
                    rootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList[0];

                    ViewModel.TempDiyLEDCols = rootDIYLedModel.DiyLEDCols;
                    ViewModel.TempDiyLEDRows = rootDIYLedModel.DiyLEDRows;
                    ViewModel.TempLedModelList = rootDIYLedModel.DiyLedModelList;

                    RootDIYLEDItemsControls.Items.Refresh();
                }
                else
                {
                    ViewModel.TempDiyLEDCols = 0;
                    ViewModel.TempDiyLEDRows = 0;
                    ViewModel.TempLedModelList = new ObservableCollection<DIYLedModel>();

                    RootDIYLEDItemsControls.Items.Refresh();
                }
            }
        }

        private void InvertRootDiyLedButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (this.ShowDialog("确认新建反选的Pattern吗？", "确定", MessageBoxButton.OKCancel, DialogIcon.Question) == MessageBoxResult.OK)
            {
                try
                {
                    DataGrid dataGrid = dataGridRootDiyLedModelName;

                    Console.WriteLine("-----------------:" + dataGrid.SelectedIndex);

                    RootDIYLedModel oldRootDIYLedModel = new RootDIYLedModel();

                    oldRootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList[dataGrid.SelectedIndex];

                    RootDIYLedModel newRootDIYLedModel = new RootDIYLedModel();

                    newRootDIYLedModel = (RootDIYLedModel)oldRootDIYLedModel.Clone();

                    string saveDir = string.Format(@"{0}DIYImages\{1}\", this.GetBaseDirectory(), ViewModel.ConfigInfo.TestConfig.Project);

                    string LEDInfoStr = System.IO.Path.GetFileNameWithoutExtension(ViewModel.ConfigInfo.TestConfig.xlsName);

                    string[] name = System.IO.Path.GetFileNameWithoutExtension(oldRootDIYLedModel.xmlPathName).Split('_');

                    string xmlDIYLEDModelPath = saveDir + (name.Count() > 0 ? name[0] : "Invert").ToString() + "_" + LEDInfoStr + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + "_Invert" + ".xml";

                    newRootDIYLedModel.xmlPathName = System.IO.Path.GetFileName(xmlDIYLEDModelPath);
                    newRootDIYLedModel.RootName = oldRootDIYLedModel.RootName + "_Invert";
                    //newRootDIYLedModel.IsTest = oldRootDIYLedModel.IsTest;
                    //newRootDIYLedModel.DiyLEDCols = oldRootDIYLedModel.DiyLEDCols;
                    //newRootDIYLedModel.DiyLEDRows = oldRootDIYLedModel.DiyLEDRows;

                    foreach (DIYLedModel model in newRootDIYLedModel.DiyLedModelList)
                    {

                        if (model.LedType == "Idle")
                        {
                            model.LedType = "Nomal";
                            model.LightValue = 100;
                            model.ReaLightCurrentValue = Math.Round(this.CompareReaCurrent(ViewModel.NewLightValue), 5);

                        }
                        else
                        {
                            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
                            {
                                model.LedType = "Idle";
                                model.ReaLightCurrentValue = 0;
                                model.LightValue = 0;
                            }
                            else
                            {
                                model.LedType = "Idle";
                                model.ReaLightCurrentValue = 0;
                                model.LightValue = 128;
                            }
                        }

                    }

                    ConfigHelper.XmlFileSerialize<RootDIYLedModel>(newRootDIYLedModel, xmlDIYLEDModelPath);


                    foreach (DIYLedModel model in oldRootDIYLedModel.DiyLedModelList)
                    {
                        if (model.LedType == "Idle")
                        {
                            model.LedType = "Nomal";
                            model.LightValue = 100;
                            model.ReaLightCurrentValue = Math.Round(this.CompareReaCurrent(ViewModel.NewLightValue), 5);

                        }
                        else
                        {
                            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
                            {
                                model.LedType = "Idle";
                                model.ReaLightCurrentValue = 0;
                                model.LightValue = 0;
                            }
                            else
                            {
                                model.LedType = "Idle";
                                model.ReaLightCurrentValue = 0;
                                model.LightValue = 128;
                            }
                        }

                    }

                    //ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList.Add(newRootDIYLedModel);

                    dataGridRootDiyLedModelName.ItemsSource = null;
                    dataGridRootDiyLedModelName.ItemsSource = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList;

                    if (ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList.Count > 0)
                    {
                        RootDIYLedModel rootDIYLedModel = new RootDIYLedModel();
                        rootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList[0];

                        ViewModel.TempDiyLEDCols = rootDIYLedModel.DiyLEDCols;
                        ViewModel.TempDiyLEDRows = rootDIYLedModel.DiyLEDRows;
                        ViewModel.TempLedModelList = rootDIYLedModel.DiyLedModelList;

                        //RootDIYLEDItemsControls.Items.Refresh();
                    }
                    else
                    {
                        ViewModel.TempDiyLEDCols = 0;
                        ViewModel.TempDiyLEDRows = 0;
                        ViewModel.TempLedModelList = new ObservableCollection<DIYLedModel>();

                        //RootDIYLEDItemsControls.Items.Refresh();
                    }

                    this.ShowPromptWindow("新建成功！", PromptType.Green);
                }
                catch
                {
                    this.ShowPromptWindow("新建失败！", PromptType.Red);
                }
            }
        }


        private void SaveXmlRootDiyLedButton_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                DataGrid dataGrid = dataGridRootDiyLedModelName;

                RootDIYLedModel oldRootDIYLedModel = new RootDIYLedModel();

                oldRootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList[dataGrid.SelectedIndex];

                string saveDir = string.Format(@"{0}DIYImages\{1}\", this.GetBaseDirectory(), ViewModel.ConfigInfo.TestConfig.Project);

                if (!System.IO.Directory.Exists(saveDir))
                {
                    System.IO.Directory.CreateDirectory(saveDir);
                }

                string LEDInfoStr = System.IO.Path.GetFileNameWithoutExtension(ViewModel.ConfigInfo.TestConfig.xlsName);

                string xmlDIYLEDModelPath = saveDir + oldRootDIYLedModel.RootName + "_" + LEDInfoStr + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".xml";

                ConfigHelper.XmlFileSerialize<RootDIYLedModel>(oldRootDIYLedModel, xmlDIYLEDModelPath);

                this.ShowPromptWindow("保存成功！", PromptType.Green);
            }
            catch
            {
                this.ShowPromptWindow("保存失败！", PromptType.Red);
            }

        }
        private void SaveCSVRootDiyLedButton_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                DataGrid dataGrid = dataGridRootDiyLedModelName;

                RootDIYLedModel oldRootDIYLedModel = new RootDIYLedModel();

                oldRootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList[dataGrid.SelectedIndex];

                string saveDir = string.Format(@"{0}DIYCurrentCSV\{1}\", this.GetBaseDirectory(), ViewModel.ConfigInfo.TestConfig.Project);

                if (!System.IO.Directory.Exists(saveDir))
                {
                    System.IO.Directory.CreateDirectory(saveDir);
                }
                string LEDInfoStr = System.IO.Path.GetFileNameWithoutExtension(ViewModel.ConfigInfo.TestConfig.xlsName);

                string DIYLEDModelcsvPath = saveDir + oldRootDIYLedModel.RootName + "_" + LEDInfoStr + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".csv";

                List<DIYLedModel> dIYLedModels = oldRootDIYLedModel.DiyLedModelList.ToList();

                using (System.IO.StreamWriter xmlsw = new System.IO.StreamWriter(DIYLEDModelcsvPath, false, Encoding.UTF8))
                {
                    StringBuilder xmlsb = new StringBuilder();

                    List<IGrouping<double, DIYLedModel>> dIYLedModelICGroup = dIYLedModels.GroupBy(t => t.Position.X).ToList();

                    foreach (IGrouping<double, DIYLedModel> ICGroup in dIYLedModelICGroup)
                    {
                        string its = "";
                        foreach (var it in ICGroup)
                        {
                            its += it.ReaLightCurrentValue + ",";
                        }
                        xmlsb.AppendLine(its);
                    }

                    xmlsw.WriteLine(xmlsb.ToString());
                    xmlsw.Close();
                }

                this.ShowPromptWindow("保存成功！", PromptType.Green);

            }
            catch
            {
                this.ShowPromptWindow("保存失败！", PromptType.Red);
            }

        }
        #endregion

        #region Temp DiyLED 操作

        /// <summary>
        /// 点击LED按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TempDiyLedButton_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;

            if (button != null)
            {
                string Name = button.Tag.ToString();

                DIYLedModel dIYLedModel = ViewModel.TempLedModelList.First(x => x.Name.Equals(Name));

                string[] LEDArr = button.Tag.ToString().Split('_');

                string strIc = LEDArr[1];
                string strLed = LEDArr[2];

                tbTempEditICName.Text = strIc;
                tbTempEditLEDIDName.Text = strLed;

                tbTempEditLightName.Text = dIYLedModel.LightValue.ToString();

                int lightValue = 0;

                if (!int.TryParse(tbTempEditLightName.Text, out lightValue))
                {

                    return;
                }

                if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
                {
                    if (lightValue < 0)
                    {
                        tbTempEditLightName.Text = "0";
                        lightValue = 0;
                    }

                    if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 17|| ViewModel.ConfigInfo.TestConfig.TestModelCode == 31)
                    {
                        if (lightValue > 16383)
                        {
                            tbTempEditLightName.Text = "16383";
                            lightValue = 16383;
                        }
                    }
                    else
                    {
                        if (lightValue > 4095)
                        {
                            tbTempEditLightName.Text = "4095";
                            lightValue = 4095;
                        }
                    }
                    tbTempEditCurrentLightName.Text = CompareReaCurrent(lightValue).ToString();

                }
                else if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 3)
                {
                    if (lightValue < 0)
                    {
                        tbTempEditLightName.Text = "0";
                        lightValue = 0;
                    }

                    if (lightValue > 65535)
                    {
                        tbTempEditLightName.Text = "65535";
                        lightValue = 65535;
                    }
                    tbTempEditCurrentLightName.Text = CompareReaCurrent(lightValue).ToString();
                }
                else
                {
                    if (lightValue < 0)
                    {
                        tbTempEditLightName.Text = "0";
                        lightValue = 0;
                    }

                    else if (lightValue >= 128)
                    {
                        tbTempEditLightName.Text = "128";

                        lightValue = 128;

                        tbTempEditCurrentLightName.Text = "0";
                    }
                    else
                    {
                        tbTempEditCurrentLightName.Text = CompareReaCurrent(lightValue).ToString();
                    }

                }

                this.SetTempLedLightGrid.Visibility = Visibility.Visible;

            }
        }


        /// <summary>
        /// Temp 点击 编辑亮度 的确定按钮事件
        /// </summary>
        private void TempEditLightOk()
        {
            int lightValue = 0;

            if (!int.TryParse(tbTempEditLightName.Text, out lightValue))
            {

                return;
            }

            double reaLightCurrentValue = double.Parse(tbTempEditCurrentLightName.Text);

            if (reaLightCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
            {
                this.ShowPromptWindow(string.Format("设置电流值:{0}大于上限值，上限值为[{1}]", reaLightCurrentValue, ViewModel.ConfigInfo.TestConfig.CurrentUpper), PromptType.Red);
                return;
            }

            string strIc = tbTempEditICName.Text;
            string strLed = tbTempEditLEDIDName.Text;

            DIYLedModel dIYLedModel = ViewModel.TempLedModelList.First(s => s.ICID == strIc && s.LEDID.ToString() == strLed);

            dIYLedModel.LightValue = lightValue;

            dIYLedModel.ReaLightCurrentValue = reaLightCurrentValue;

            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {

                if (lightValue != 0)
                {
                    dIYLedModel.LedType = "Nomal";
                }
                else
                {
                    dIYLedModel.LedType = "Idle";
                }

            }
            else
            {
                if (lightValue != 128)
                {
                    dIYLedModel.LedType = "Nomal";
                }
                else
                {
                    dIYLedModel.LedType = "Idle";
                }
            }

            this.SetTempLedLightGrid.Visibility = Visibility.Collapsed;

            if (CurrentSelectRootDIYLedModel.xmlPathName != null)
            {
                string saveDir = string.Format(@"{0}DIYImages\{1}\", this.GetBaseDirectory(), ViewModel.ConfigInfo.TestConfig.Project);
                string xmlDIYLEDModelPath = saveDir + System.IO.Path.GetFileName(CurrentSelectRootDIYLedModel.xmlPathName);
                ConfigHelper.XmlFileSerialize<RootDIYLedModel>(CurrentSelectRootDIYLedModel, xmlDIYLEDModelPath);
            }
            //RootDIYLEDItemsControls.ItemsSource = null;
            //RootDIYLEDItemsControls.ItemsSource = ViewModel.TempLedModelList;

        }

        /// <summary>
        /// 编辑Temp 亮度框值改变触发事件，修改真实电流值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbEditTempLightName_TextChanged(object sender, TextChangedEventArgs e)
        {
            int lightValue = 0;

            if (!int.TryParse(tbTempEditLightName.Text, out lightValue))
            {

                return;
            }

            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                if (lightValue < 0)
                {
                    tbTempEditLightName.Text = "0";
                    lightValue = 0;
                }

                if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 17 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 31)
                {
                    if (lightValue > 16383)
                    {
                        tbTempEditLightName.Text = "16383";
                        lightValue = 16383;
                    }
                }
                else
                {
                    if (lightValue > 4095)
                    {
                        tbTempEditLightName.Text = "4095";
                        lightValue = 4095;
                    }
                }

                tbTempEditCurrentLightName.Text = CompareReaCurrent(lightValue).ToString();

            }else if(ViewModel.ConfigInfo.TestConfig.TestCaseType == 3)
            {
                if (lightValue < 0)
                {
                    tbTempEditLightName.Text = "0";
                    lightValue = 0;
                }

                if (lightValue > 65535)
                {
                    tbTempEditLightName.Text = "65535";
                    lightValue = 65535;
                }
                tbTempEditCurrentLightName.Text = CompareReaCurrent(lightValue).ToString();
            }
            else
            {
                if (lightValue < 0)
                {
                    tbTempEditLightName.Text = "0";
                    lightValue = 0;
                }

                else if (lightValue >= 128)
                {
                    tbTempEditLightName.Text = "128";

                    lightValue = 128;

                    tbTempEditCurrentLightName.Text = "0";
                }
                else
                {
                    tbTempEditCurrentLightName.Text = CompareReaCurrent(lightValue).ToString();
                }

            }

        }


        #region 鼠标在Temp LED Button上移动和离开时触发的事件
        private void TempDIYLed_MouseMove(object sender, MouseEventArgs e)
        {
            Button button = sender as Button;

            string Name = button.Tag.ToString();

            DIYLedModel dIYLedModel = ViewModel.TempLedModelList.First(x => x.Name.Equals(Name));

            tbTempLedInfoName.Text = Name + " 亮度：" + dIYLedModel.LightValue.ToString() + " 电流值:" + dIYLedModel.ReaLightCurrentValue + "mA";
        }

        private void TempDIDLed_MouseLeave(object sender, MouseEventArgs e)
        {
            tbTempLedInfoName.Text = "";
        }

        #endregion

        #endregion

        #region 新增 Pattern 
        private void NewDIYLedButton_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;

            if (button != null && IsShiftKeyDown == false && IsCtrlKeyDown == false)
            {
                string Name = button.Tag.ToString();

                DIYLedModel dIYLedModel = ViewModel.NewLedModelList.First(x => x.Name.Equals(Name));

                dIYLedModel.LedType = "Idle";

                if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
                {
                    dIYLedModel.LightValue = 0;
                }
                else
                {
                    dIYLedModel.LightValue = 128;
                }
                dIYLedModel.ReaLightCurrentValue = 0;
            }

            if (button != null && IsShiftKeyDown == true)
            {
                string Name = button.Tag.ToString();

                DIYLedModel dIYLedModel = ViewModel.NewLedModelList.First(x => x.Name.Equals(Name));

                string[] LEDArr = button.Tag.ToString().Split('_');

                string strIc = LEDArr[1];
                string strLed = LEDArr[2];

                tbEditICName.Text = strIc;
                tbEditLEDIDName.Text = strLed;

                tbEditLightName.Text = dIYLedModel.LightValue.ToString();

                this.SetLedLightGrid.Visibility = Visibility.Visible;

            }
        }

        private void NewDIYLed_MouseMove(object sender, MouseEventArgs e)
        {
            Button button = sender as Button;

            this.borderNewDIYLEDName.ForceCursor = true;
            this.borderNewDIYLEDName.Focus();

            if (button != null && IsCtrlKeyDown)
            {
                string Name = button.Tag.ToString();

                DIYLedModel dIYLedModel = ViewModel.NewLedModelList.First(x => x.Name.Equals(Name));

                if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
                {
                    double reaLightCurrentValue = Math.Round(this.CompareReaCurrent(ViewModel.NewLightValue), 5);
                    if (reaLightCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
                    {
                        this.ShowPromptWindow(string.Format("设置电流值:{0}大于上限值，上限值为[{1}]",reaLightCurrentValue, ViewModel.ConfigInfo.TestConfig.CurrentUpper), PromptType.Red);
                        IsCtrlKeyDown = false;
                        return;
                    }

                    dIYLedModel.LedType = "Nomal";

                    dIYLedModel.LightValue = ViewModel.NewLightValue;

                    dIYLedModel.ReaLightCurrentValue = reaLightCurrentValue;//Math.Round(this.CompareReaCurrent(dIYLedModel.LightValue), 5);

                }
                else
                {
                    if (ViewModel.NewLightValue == 128)
                    {
                        dIYLedModel.LedType = "Idle";

                        dIYLedModel.LightValue = ViewModel.NewLightValue;

                        dIYLedModel.ReaLightCurrentValue = 0;
                    }
                    else
                    {
                        double reaLightCurrentValue = Math.Round(this.CompareReaCurrent(ViewModel.NewLightValue), 5);
                        if (reaLightCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
                        {
                            return;
                        }

                        dIYLedModel.LedType = "Nomal";

                        dIYLedModel.LightValue = ViewModel.NewLightValue;

                        dIYLedModel.ReaLightCurrentValue = reaLightCurrentValue;//Math.Round(this.CompareReaCurrent(dIYLedModel.LightValue), 5);
                    }

                }

            }

            if(button != null && !IsCtrlKeyDown) {

                string Name = button.Tag.ToString();

                DIYLedModel dIYLedModel = ViewModel.NewLedModelList.First(x => x.Name.Equals(Name));

                tbLedInfoName.Text = Name + " 亮度：" + dIYLedModel.LightValue.ToString() + " 电流值:" + dIYLedModel.ReaLightCurrentValue + "mA";
            }

        }

        private bool IsCtrlKeyDown = false;

        private bool IsShiftKeyDown = false;

        private void borderNewDIYLEDName_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
            {
               
                IsCtrlKeyDown = true;
                Console.WriteLine("Ctrl KeyDown");
            }
            if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
            {

                IsShiftKeyDown = true;
                Console.WriteLine("Shift KeyDown");
            }

        }

        private void borderNewDIYLEDName_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
            {
                IsCtrlKeyDown = false;

                Console.WriteLine("Ctrl KeyUp");
            }
            if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
            {

                IsShiftKeyDown = false;
                Console.WriteLine("Shift KeyUp");
            }
        }


        private void EditLightOk()
        {
            int lightValue = 0;

            if (!int.TryParse(tbEditLightName.Text, out lightValue))
            {

                return;
            }

            double reaLightCurrentValue = double.Parse(tbEditCurrentLightName.Text);

            if (reaLightCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
            {
                this.ShowPromptWindow(string.Format("设置电流值:{0}大于上限值，上限值为[{1}]", reaLightCurrentValue, ViewModel.ConfigInfo.TestConfig.CurrentUpper), PromptType.Red);
                return;
            }

            string strIc = tbEditICName.Text;
            string strLed = tbEditLEDIDName.Text;

            DIYLedModel dIYLedModel = ViewModel.NewLedModelList.First(s => s.ICID == strIc && s.LEDID.ToString() == strLed);

            dIYLedModel.LightValue = lightValue;


            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                if (lightValue != 0)
                {
                    dIYLedModel.LedType = "Nomal";
                }
                else
                {
                    dIYLedModel.LedType = "Idle";
                }
            }
            else
            {

                if (lightValue != 128)
                {
                    dIYLedModel.LedType = "Nomal";
                }
                else
                {
                    dIYLedModel.LedType = "Idle";
                }
            }

            dIYLedModel.ReaLightCurrentValue = reaLightCurrentValue;

            this.SetLedLightGrid.Visibility = Visibility.Collapsed;

            NewRootDIYLEDItemsControls.ItemsSource = null;
            NewRootDIYLEDItemsControls.ItemsSource = ViewModel.NewLedModelList;

        }

        private void tbEditLightName_TextChanged(object sender, TextChangedEventArgs e)
        {

            int lightValue = 0;

            if (!int.TryParse(tbEditLightName.Text, out lightValue))
            {

                return;
            }

            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1  || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                if (lightValue < 0)
                {
                    tbEditLightName.Text = "0";
                    lightValue = 0;
                }

                if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 17 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 31)
                {
                    if (lightValue > 16383)
                    {
                        tbEditLightName.Text = "16383";
                        lightValue = 16383;
                    }
                }
                else
                {
                    if (lightValue > 4095)
                    {
                        tbEditLightName.Text = "4095";
                        lightValue = 4095;
                    }
                }
                tbEditCurrentLightName.Text = CompareReaCurrent(lightValue).ToString();

            }
            else if(ViewModel.ConfigInfo.TestConfig.TestCaseType == 3)
            {
                if (lightValue < 0)
                {
                    tbEditLightName.Text = "0";
                    lightValue = 0;
                }

                if (lightValue > 65535)
                {
                    tbEditLightName.Text = "65535";
                    lightValue = 65535;
                }
                tbEditCurrentLightName.Text = CompareReaCurrent(lightValue).ToString();
            }
            else
            {
                if (lightValue < 0)
                {
                    tbEditLightName.Text = "0";
                    lightValue = 0;
                }
                else if (lightValue >= 128)
                {
                    tbEditLightName.Text = "128";

                    lightValue = 128;

                    tbEditCurrentLightName.Text = "0";
                }
                else
                {
                    tbEditCurrentLightName.Text = CompareReaCurrent(lightValue).ToString();
                }
               
            }

        }

        private void Button_MouseLeave(object sender, MouseEventArgs e)
        {
            tbLedInfoName.Text = "";
        }


        #endregion

        #region 棋盘格设置
        private void DeleteRootQiPanLedButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (this.ShowDialog("确认删除？", "确定", MessageBoxButton.OKCancel, DialogIcon.Question) == MessageBoxResult.OK)
            {

                DataGrid dataGrid = dataGridRootQiPanLedModelName;

                Console.WriteLine("-----------------:" + dataGrid.SelectedIndex);

                ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList.RemoveRange(dataGrid.SelectedIndex, 1);

                dataGridRootQiPanLedModelName.ItemsSource = null;
                dataGridRootQiPanLedModelName.ItemsSource = ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList;

                if (ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList.Count > 0)
                {
                    RootDIYLedModel rootDIYLedModel = new RootDIYLedModel();
                    rootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList[0];

                    ViewModel.TempDiyQiPanLEDCols = rootDIYLedModel.DiyLEDCols;
                    ViewModel.TempDiyQiPanLEDRows = rootDIYLedModel.DiyLEDRows;
                    ViewModel.TempQiPanLedModelList = rootDIYLedModel.DiyLedModelList;

                    RootQiPanLEDItemsControls.Items.Refresh();
                }
                else
                {
                    ViewModel.TempDiyQiPanLEDCols = 0;
                    ViewModel.TempDiyQiPanLEDRows = 0;
                    ViewModel.TempQiPanLedModelList = new ObservableCollection<DIYLedModel>();

                    RootQiPanLEDItemsControls.Items.Refresh();
                }
            }
        }

        private void dataGridRootQiPanLedModelName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataGrid dataGrid = sender as DataGrid;

            Console.WriteLine("-----------------:" + dataGrid.SelectedIndex);

            if (dataGrid.SelectedIndex >= 0)
            {
                RootDIYLedModel rootDIYLedModel = new RootDIYLedModel();
                rootDIYLedModel = ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList[dataGrid.SelectedIndex];

                ViewModel.TempDiyQiPanLEDCols = rootDIYLedModel.DiyLEDCols;
                ViewModel.TempDiyQiPanLEDRows = rootDIYLedModel.DiyLEDRows;
                ViewModel.TempQiPanLedModelList = rootDIYLedModel.DiyLedModelList;

                RootQiPanLEDItemsControls.Items.Refresh();
            }
        }
        
        #endregion

        #region TextBox_Changed
        private void MCText_Changed(object sender, TextChangedEventArgs e)
        {
            Console.WriteLine("#####");
            
            if (ViewModel.ConfigInfo.TestConfig.IMCValue < 0)
            {
                ViewModel.ConfigInfo.TestConfig.IMCValue = 0;
            }

            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                if (ViewModel.ConfigInfo.TestConfig.IMCValue > 255)
                {
                    ViewModel.ConfigInfo.TestConfig.IMCValue = 255;
                }
                
            }
            else
            {
                if (ViewModel.ConfigInfo.TestConfig.IMCValue > 7)
                {
                    ViewModel.ConfigInfo.TestConfig.IMCValue = 7;
                }
            }
            
        }
        private void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // 检查输入的字符是否为数字
            if (!char.IsDigit(e.Text, e.Text.Length - 1))
            {
                e.Handled = true;
            }
        }
        private void DCText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.IDCValue < 1)
            {
                ViewModel.ConfigInfo.TestConfig.IDCValue = 1;
            }
           
            if (ViewModel.ConfigInfo.TestConfig.IDCValue > 127)
            {
                ViewModel.ConfigInfo.TestConfig.IDCValue = 127;
            }
            
        }

        private void BCText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.IBCValue < 1)
            {
                ViewModel.ConfigInfo.TestConfig.IBCValue = 1;
            }

            if (ViewModel.ConfigInfo.TestConfig.IBCValue > 127)
            {
                ViewModel.ConfigInfo.TestConfig.IBCValue = 127;
            }
        }
        private void SCALEText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.IScaleValue < 0)
            {
                ViewModel.ConfigInfo.TestConfig.IScaleValue = 0;
            }

            if (ViewModel.ConfigInfo.TestConfig.IScaleValue > 3)
            {
                ViewModel.ConfigInfo.TestConfig.IScaleValue = 3;
            }
        }

        private void SRCText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.ISrcValue < 0)
            {
                ViewModel.ConfigInfo.TestConfig.ISrcValue = 0;
            }

            if (ViewModel.ConfigInfo.TestConfig.ISrcValue > 31)
            {
                ViewModel.ConfigInfo.TestConfig.ISrcValue = 31;
            }
        }

        private void RSETText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.IRSETValue < 1)
            {
                ViewModel.ConfigInfo.TestConfig.IRSETValue = 1;
            }

            if (ViewModel.ConfigInfo.TestConfig.IRSETValue > 65535)
            {
                ViewModel.ConfigInfo.TestConfig.IRSETValue = 65535;
            }
        }

        private void ILEDText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.IILEDValue < 0)
            {
                ViewModel.ConfigInfo.TestConfig.IILEDValue = 0;
            }

            if (ViewModel.ConfigInfo.TestConfig.IILEDValue > 63)
            {
                ViewModel.ConfigInfo.TestConfig.IILEDValue = 63;
            }
        }

        private void DIYPictureSetMCCText_Changed(object sender, TextChangedEventArgs e)
        {

            if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC < 0)
            {
                ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC = 0;
            }


            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC > 255)
                {
                    ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC = 255;
                }

            }
            else
            {
                if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC > 7)
                {
                    ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC = 7;
                }
            }

        }

        private void DIYPictureSetBCText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetBC < 0)
            {
                ViewModel.ConfigInfo.TestConfig.DIYPictureSetBC = 0;
            }


            if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetBC > 127)
            {
                ViewModel.ConfigInfo.TestConfig.DIYPictureSetBC = 127;
            }
        }
        
        private void DIYPictureSetValueText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue < 0)
            {
                ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = 0;
            }

            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 7)
            {
                if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue > 4095)
                {
                    ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = 4095;
                }
            }
            else if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue > 33333)
                {
                    ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = 33333;
                }
            }
            else if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 6)
            {
                if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue > 4095)
                {
                    ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = 4095;
                }
            }
            else if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 4)
            {
                if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 17 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 31)
                {
                    if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue > 16383)
                    {
                        ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = 16383;
                    }
                }
                else
                {
                    if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue > 4095)
                    {
                        ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = 4095;
                    }
                }
            }
            else
            {
                if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue > 65535)
                {
                    ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue = 65535;
                }
            }
        }
        private void DIYPictureSetScaleCText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetScale < 0)
            {
                ViewModel.ConfigInfo.TestConfig.DIYPictureSetScale = 0;
            }


            if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetScale > 3)
            {
                ViewModel.ConfigInfo.TestConfig.DIYPictureSetScale = 3;
            }
        }

        private void DIYPictureSetILEDText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetILED < 0)
            {
                ViewModel.ConfigInfo.TestConfig.DIYPictureSetILED = 0;
            }


            if (ViewModel.ConfigInfo.TestConfig.DIYPictureSetILED > 63)
            {
                ViewModel.ConfigInfo.TestConfig.DIYPictureSetILED = 63;
            }
        }

        private void CheckerBoardMCText_Changed(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.CheckerBoardSetMC < 0)
            {
                ViewModel.ConfigInfo.TestConfig.CheckerBoardSetMC = 0;
            }
            if (ViewModel.ConfigInfo.TestConfig.CheckerBoardSetMC > 255)
            {
                ViewModel.ConfigInfo.TestConfig.CheckerBoardSetMC = 255;
            }

        }

        private void CheckerBoardText_Changed(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;

            int ivalue = 0;

            if (int.TryParse(textBox.Text, out ivalue))
            {
                if (ivalue < 0)
                {
                    textBox.Text = "0";
                }
                if (ivalue > 4095)
                {
                    textBox.Text = "4095";
                }
            }
        }
        #endregion

        #region TestItem 设置值文本框改变时触发
        private void SetCurrentText_Changed(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;

            
            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                
                int SetCurrentValue = 0;

                if (int.TryParse(textBox.Text, out SetCurrentValue))
                {
                    if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 17 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 31)
                    {
                        if (SetCurrentValue > 16383)
                        {
                            textBox.Text = "16383";
                        }
                    }
                    else
                    {
                        if (SetCurrentValue > 4095)
                        {
                            textBox.Text = "4095";
                        }
                    }
                    if (SetCurrentValue < 0)
                    {
                        textBox.Text = "0";
                    }
                }
            }
            else
            {
                int SetCurrentValue = 0;

                if (int.TryParse(textBox.Text, out SetCurrentValue))
                {
                    if (SetCurrentValue > 65535)
                    {
                        textBox.Text = "65535";
                    }
                    if (SetCurrentValue < 0)
                    {
                        textBox.Text = "0";
                    }
                }
            }

            ComparerTestItemCurrentValue();
        }

        private void SetTestItemMCText_Changed(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;

            int MC = 0;

            if(int.TryParse(textBox.Text, out MC))
            {
                if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
                {
                    if (MC > 255)
                    {
                        textBox.Text = "255";
                    }
                    if (MC < 0)
                    {
                        textBox.Text = "0";
                    }

                }
                else
                {
                    if (MC > 7)
                    {
                        textBox.Text = "7";
                    }
                    if (MC < 0)
                    {
                        textBox.Text = "0";
                    }
                }
            }
            
            ComparerTestItemCurrentValue();
        }

        private void SetTestItemDCText_Changed(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;

            int DC = 0;

            if (int.TryParse(textBox.Text, out DC))
            {
                if (DC > 127)
                {
                    textBox.Text = "127";
                }
                if (DC < 0)
                {
                    textBox.Text = "0";
                }
            }

            ComparerTestItemCurrentValue();
        }

        private void SetTestItemBCText_Changed(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;

            int BC = 0;

            if (int.TryParse(textBox.Text, out BC))
            {
                if (BC > 127)
                {
                    textBox.Text = "127";
                }
                if (BC < 0)
                {
                    textBox.Text = "0";
                }
            }
            ComparerTestItemCurrentValue();
        }

        private void SetTestItemScaleText_Changed(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;

            int Scale = 0;

            if (int.TryParse(textBox.Text, out Scale))
            {
                if (Scale > 3)
                {
                    textBox.Text = "3";
                }
                if (Scale < 0)
                {
                    textBox.Text = "0";
                }
            }

            ComparerTestItemCurrentValue();
        }

        private void SetTestItemILEDText_Changed(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;

            int ILed = 0;

            if (int.TryParse(textBox.Text, out ILed))
            {
                if (ILed > 63)
                {
                    textBox.Text = "63";
                }
                if (ILed < 0)
                {
                    textBox.Text = "0";
                }
            }
            ComparerTestItemCurrentValue();
        }

        private void TextBox_LostSetFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = e.Source as TextBox;

            Console.WriteLine(tb.Text);
            if (tb.Text == "")
            {
                tb.Text = "0";
            }
        }

        #region 计算testItem设置的真实值
        //public void ComparerTestItemCurrentValue1()
        //{
        //    if (ViewModel.ConfigInfo.TestConfig.TestItems != null)
        //    {
        //        foreach (TestItem testItem in ViewModel.ConfigInfo.TestConfig.TestItems)
        //        {
        //            if (!testItem.IsReaValue)
        //            {
        //                continue;
        //            }

        //            int coefficientCase = 0;

        //            double ISCurrentValue = 0;

        //            int iType = 0;

        //            switch (ViewModel.ConfigInfo.TestConfig.TestCaseType)
        //            {
        //                case 1:
        //                    {
        //                        coefficientCase = 4095;
        //                        ISCurrentValue = 12.5;
        //                        iType = 1;
        //                        if(ViewModel.ConfigInfo.TestConfig.IC_PinCount == 0)
        //                        {
        //                            ViewModel.ConfigInfo.TestConfig.IC_PinCount = 16;
        //                        }
        //                    }
        //                    break;
        //                case 4:
        //                    {
        //                        coefficientCase = 4095;
        //                        ISCurrentValue = 12.5;
        //                        iType = 4;
        //                        if (ViewModel.ConfigInfo.TestConfig.IC_PinCount == 0)
        //                        {
        //                            ViewModel.ConfigInfo.TestConfig.IC_PinCount = 100;
        //                        }
        //                    }
        //                    break;
        //                case 2:
        //                    {
        //                        coefficientCase = 65535;
        //                        ISCurrentValue = 5.8;
        //                        iType = 2;
        //                        if (ViewModel.ConfigInfo.TestConfig.IC_PinCount == 0)
        //                        {
        //                            ViewModel.ConfigInfo.TestConfig.IC_PinCount = 48;
        //                        }
        //                    }
        //                    break;
        //                case 7:
        //                    {

        //                    }
        //                    break;
        //                case 3:
        //                    {
        //                        coefficientCase = 65535;
        //                        ISCurrentValue = 6.3;
        //                        iType = 3;
        //                        if (ViewModel.ConfigInfo.TestConfig.IC_PinCount == 0)
        //                        {
        //                            ViewModel.ConfigInfo.TestConfig.IC_PinCount = 38;
        //                        }
        //                    }
        //                    break;

        //                default:
        //                    break;
        //            }

        //            if (iType == 1)
        //            {
        //                double dRealityCurrentValue = Math.Round((((60 * testItem.SetMcValue) / 255.0) * testItem.SetCurrentValue)/coefficientCase, 5);  //Math.Round((ViewModel.ConfigInfo.TestConfig.IoutCurrentValue * testItem.SetCurrentValue) / coefficientCase, 5);

        //                testItem.RealityCurrentValue = dRealityCurrentValue.ToString();// + "mA";

        //                if(testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
        //                {
        //                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.IC_PinCount), 3).ToString();
        //                }
        //                else 
        //                {
        //                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.LEDCount),3).ToString();
        //                }

        //                if (dRealityCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
        //                {
        //                    testItem.IsRealityCurrentValueLimit = "false";
        //                }
        //                else
        //                {
        //                    testItem.IsRealityCurrentValueLimit = "true";
        //                }

        //            }
        //            else if(iType == 2)
        //            {

        //                double dOutCurrentValue = ComputeIoutForBH003_Bh004(testItem.SetMcValue, testItem.SetDcValue, testItem.SetBcValue);

        //                double dRealityCurrentValue = Math.Round((dOutCurrentValue * testItem.SetCurrentValue) / coefficientCase, 5);

        //                testItem.RealityCurrentValue = dRealityCurrentValue.ToString();// + "mA";

        //                if (testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
        //                {
        //                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.IC_PinCount),3).ToString();
        //                }
        //                else
        //                {
        //                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.LEDCount),3).ToString();
        //                }

        //                if (dRealityCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
        //                {
        //                    testItem.IsRealityCurrentValueLimit = "false";
        //                }
        //                else
        //                {
        //                    testItem.IsRealityCurrentValueLimit = "true";
        //                }

        //            }else if(iType == 3)//Iout=(2+2*XA+(0.25+XA*0.25)*XB)*XC/65535=0;
        //            {

        //                double dRealityCurrentValue = Math.Round((2 + 2*testItem.SetScaleValue +((0.25 + testItem.SetScaleValue * 0.25) * testItem.SetILedValue)) * testItem.SetCurrentValue / coefficientCase, 5);

        //                testItem.RealityCurrentValue = dRealityCurrentValue.ToString();// + "mA";

        //                if (testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
        //                {
        //                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.IC_PinCount), 3).ToString();
        //                }
        //                else
        //                {
        //                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.LEDCount), 3).ToString();
        //                }

        //                if (dRealityCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
        //                {
        //                    testItem.IsRealityCurrentValueLimit = "false";
        //                }
        //                else
        //                {
        //                    testItem.IsRealityCurrentValueLimit = "true";
        //                }
        //            }

        //        }
        //    }

        //}
        public void ComparerTestItemCurrentValue()
        {
            if (ViewModel.ConfigInfo.TestConfig.TestItems != null)
            {
                foreach (TestItem testItem in ViewModel.ConfigInfo.TestConfig.TestItems)
                {
                    if (!testItem.IsReaValue)
                    {
                        continue;
                    }

                    int coefficientCase = 0;

                    switch (ViewModel.ConfigInfo.TestConfig.TestCaseType)
                    {
                        case 1:
                            {
                                coefficientCase = 4095;

                                if (ViewModel.ConfigInfo.TestConfig.IC_PinCount == 0)
                                {
                                    ViewModel.ConfigInfo.TestConfig.IC_PinCount = 16;
                                }

                                double dRealityCurrentValue = Math.Round((((60 * testItem.SetMcValue) / 255.0) * testItem.SetCurrentValue) / coefficientCase, 5);

                                testItem.RealityCurrentValue = dRealityCurrentValue.ToString();

                                if (testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
                                {
                                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.IC_PinCount), 3).ToString();
                                }
                                else
                                {
                                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.LEDCount), 3).ToString();
                                }

                                if (dRealityCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
                                {
                                    testItem.IsRealityCurrentValueLimit = "false";
                                }
                                else
                                {
                                    testItem.IsRealityCurrentValueLimit = "true";
                                }

                            }
                            break;
                        case 2:
                            {
                                coefficientCase = 65535;

                                if (ViewModel.ConfigInfo.TestConfig.IC_PinCount == 0)
                                {
                                    ViewModel.ConfigInfo.TestConfig.IC_PinCount = 48;
                                }

                                double dOutCurrentValue = ComputeIoutForBH003_Bh004(testItem.SetMcValue, testItem.SetDcValue, testItem.SetBcValue);

                                double dRealityCurrentValue = Math.Round((dOutCurrentValue * testItem.SetCurrentValue) / coefficientCase, 5);

                                testItem.RealityCurrentValue = dRealityCurrentValue.ToString();// + "mA";

                                if (testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
                                {
                                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.IC_PinCount), 3).ToString();
                                }
                                else
                                {
                                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.LEDCount), 3).ToString();
                                }

                                if (dRealityCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
                                {
                                    testItem.IsRealityCurrentValueLimit = "false";
                                }
                                else
                                {
                                    testItem.IsRealityCurrentValueLimit = "true";
                                }
                            }
                            break;
                        case 3:
                            {
                                coefficientCase = 65535;

                                if (ViewModel.ConfigInfo.TestConfig.IC_PinCount == 0)
                                {
                                    ViewModel.ConfigInfo.TestConfig.IC_PinCount = 38;
                                }

                                double dRealityCurrentValue = Math.Round((2 + 2 * testItem.SetScaleValue + ((0.25 + testItem.SetScaleValue * 0.25) * testItem.SetILedValue)) * testItem.SetCurrentValue / coefficientCase, 5);

                                testItem.RealityCurrentValue = dRealityCurrentValue.ToString();// + "mA";

                                if (testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
                                {
                                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.IC_PinCount), 3).ToString();
                                }
                                else
                                {
                                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.LEDCount), 3).ToString();
                                }

                                if (dRealityCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
                                {
                                    testItem.IsRealityCurrentValueLimit = "false";
                                }
                                else
                                {
                                    testItem.IsRealityCurrentValueLimit = "true";
                                }
                            }
                            break;
                        case 4:
                            {
                                if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 17 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 31)
                                {
                                    coefficientCase = 16383;
                                }
                                else
                                {
                                    coefficientCase = 4095;
                                }

                                if (ViewModel.ConfigInfo.TestConfig.IC_PinCount == 0)
                                {
                                    ViewModel.ConfigInfo.TestConfig.IC_PinCount = 16;
                                }

                                double dRealityCurrentValue = Math.Round((((30 * testItem.SetMcValue) / 255.0) * testItem.SetCurrentValue) / coefficientCase, 5);  //Math.Round((ViewModel.ConfigInfo.TestConfig.IoutCurrentValue * testItem.SetCurrentValue) / coefficientCase, 5);

                                testItem.RealityCurrentValue = dRealityCurrentValue.ToString();// + "mA";

                                if (testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
                                {
                                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.IC_PinCount), 3).ToString();
                                }
                                else
                                {
                                    testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.LEDCount), 3).ToString();
                                }

                                if (dRealityCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
                                {
                                    testItem.IsRealityCurrentValueLimit = "false";
                                }
                                else
                                {
                                    testItem.IsRealityCurrentValueLimit = "true";
                                }
                            }
                            break;
                        //case 5:
                        //    {
                        //        coefficientCase = 33333;

                        //        double dOutCurrentValue = ComputeIoutForTM103(testItem.SetScaleValue, testItem.SetSRCValue);

                        //        double dRealityCurrentValue = Math.Round((dOutCurrentValue * testItem.SetCurrentValue) / coefficientCase, 5);

                        //        testItem.RealityCurrentValue = dRealityCurrentValue.ToString();// + "mA";

                        //        if (testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
                        //        {
                        //            testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.IC_PinCount), 3).ToString();
                        //        }
                        //        else
                        //        {
                        //            testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.LEDCount), 3).ToString();
                        //        }

                        //        if (dRealityCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
                        //        {
                        //            testItem.IsRealityCurrentValueLimit = "false";
                        //        }
                        //        else
                        //        {
                        //            testItem.IsRealityCurrentValueLimit = "true";
                        //        }
                        //    }
                        //    break;
                        //case 6:
                        //    {
                        //        coefficientCase = 4095;

                        //        double dOutCurrentValue = ComputeIoutForL1810(testItem.SetGCG1Value, testItem.SetGCG2Value, testItem.SetHLMSValue);

                        //        double dRealityCurrentValue = Math.Round((dOutCurrentValue * testItem.SetCurrentValue) / coefficientCase / 4, 5);

                        //        testItem.RealityCurrentValue = dRealityCurrentValue.ToString();// + "mA";

                        //        if (testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
                        //        {
                        //            testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.IC_PinCount), 3).ToString();
                        //        }
                        //        else
                        //        {
                        //            testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.LEDCount), 3).ToString();
                        //        }

                        //        if (dRealityCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
                        //        {
                        //            testItem.IsRealityCurrentValueLimit = "false";
                        //        }
                        //        else
                        //        {
                        //            testItem.IsRealityCurrentValueLimit = "true";
                        //        }


                        //    }
                        //    break;
                        //case 7:
                        //    {
                        //        coefficientCase = 4095;

                        //        double dOutCurrentValue = ComputeIoutForNLCJ663(testItem.SetMcValue, testItem.SetDcValue, testItem.SetBcValue);

                        //        double dRealityCurrentValue = Math.Round((dOutCurrentValue * testItem.SetCurrentValue) / coefficientCase, 5);

                        //        testItem.RealityCurrentValue = dRealityCurrentValue.ToString();// + "mA";

                        //        if (testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
                        //        {
                        //            testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.IC_PinCount), 3).ToString();
                        //        }
                        //        else
                        //        {
                        //            testItem.RealityTotalCurrentValue = Math.Round((dRealityCurrentValue * ViewModel.ConfigInfo.TestConfig.LEDCount), 3).ToString();
                        //        }

                        //        if (dRealityCurrentValue > ViewModel.ConfigInfo.TestConfig.CurrentUpper)
                        //        {
                        //            testItem.IsRealityCurrentValueLimit = "false";
                        //        }
                        //        else
                        //        {
                        //            testItem.IsRealityCurrentValueLimit = "true";
                        //        }
                        //    }
                        //    break;
                        default:
                            break;
                    }

                }
            }

        }

        private double ComputeIoutForBH003_Bh004(int iMCValue,int iDCValue,int iBCValue)
        {
            double iMax = 0.0;
            int MC = 0;
            int DC = 0;
            int BC = 0;

            BC = iBCValue;
            DC = iDCValue;
            MC = iMCValue;

            switch (MC)
            {
                case 0:
                    {
                        iMax = 3.2;
                    }
                    break;
                case 1:
                    {
                        iMax = 8.0;
                    }
                    break;
                case 2:
                    {
                        iMax = 11.2;
                    }
                    break;
                case 3:
                    {
                        iMax = 15.9;
                    }
                    break;
                case 4:
                    {
                        iMax = 19.1;
                    }
                    break;
                case 5:
                    {
                        iMax = 23.9;
                    }
                    break;
                case 6:
                    {
                        iMax = 27.1;
                    }
                    break;
                case 7:
                    {
                        iMax = 31.9;
                    }
                    break;
                default:
                    break;
            }

            return Math.Round(iMax * (0.262 + 0.738 * DC / 127) * (0.1 + 0.9 * BC / 127), 3);
        }

        #endregion

        #endregion

        private double CompareReaCurrent(int lightValue)
        {
            int coefficientCase = 0;

            double ReaCurrentValue = 0;

            switch (ViewModel.ConfigInfo.TestConfig.TestCaseType)
            {
                case 1:
                    {
                        coefficientCase = 4095;

                        int MC = 0;

                        MC = ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC;

                        double Iout = Math.Round(60.0 * MC / 255, 3);

                        ReaCurrentValue = Math.Round((Iout * lightValue) / coefficientCase, 5);
                    }
                    break;
                case 4:
                    {
                        if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 17 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 31)
                        {
                            coefficientCase = 16383;
                        }
                        else
                        {
                            coefficientCase = 4095;
                        }

                        int MC = 0;

                        MC = ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC;

                        double Iout = Math.Round(30.0 * MC / 255, 3);

                        ReaCurrentValue = Math.Round((Iout * lightValue) / coefficientCase, 5);
                    }
                    break;
                case 2:
                    {
                        double iMax = 0.0;
                        int MC = 0;
                        
                        int BC = 0;

                        int Value = 0;

                        BC = ViewModel.ConfigInfo.TestConfig.DIYPictureSetBC;

                        MC = ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC;

                        Value = ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue;

                        switch (MC)
                        {
                            case 0:
                                {
                                    iMax = 3.2;
                                }
                                break;
                            case 1:
                                {
                                    iMax = 8.0;
                                }
                                break;
                            case 2:
                                {
                                    iMax = 11.2;
                                }
                                break;
                            case 3:
                                {
                                    iMax = 15.9;
                                }
                                break;
                            case 4:
                                {
                                    iMax = 19.1;
                                }
                                break;
                            case 5:
                                {
                                    iMax = 23.9;
                                }
                                break;
                            case 6:
                                {
                                    iMax = 27.1;
                                }
                                break;
                            case 7:
                                {
                                    iMax = 31.9;
                                }
                                break;
                            default:
                                break;
                        }

                        coefficientCase = 65535;

                        ReaCurrentValue = Math.Round((iMax * (0.262 + 0.738 * lightValue / 127) * (0.1 + 0.9 * BC / 127)) * Value/65535, 3);
                    }
                    break;
                case 7:
                    {
                        //coefficientCase = 65535 / ViewModel.ConfigInfo.TestConfig.ILEDNUMValue;
                        //ReaCurrentValue = Math.Round((ViewModel.ConfigInfo.TestConfig.IoutCurrentValue * lightValue) / coefficientCase, 5);
                    }
                    break;
                case 3:
                    {
                        coefficientCase = 65535;

                        int Scale = ViewModel.ConfigInfo.TestConfig.DIYPictureSetScale;
                        int ILed = ViewModel.ConfigInfo.TestConfig.DIYPictureSetILED;

                        ReaCurrentValue = Math.Round((2 + 2 * Scale + ((0.25 + Scale * 0.25) * ILed)) * lightValue / coefficientCase, 5);
                    }
                    break;
                default:
                    break;
            }

            return ReaCurrentValue;
        }

        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            TextBox textBox = e.Source as TextBox;

            textBox.Focus();

            e.Handled = true;
        }

        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = e.Source as TextBox;

            Console.WriteLine(tb.Text);

            if(tb.Text == "")
            {
                tb.Text = "0";
            }

            foreach (TestItem testItem in ViewModel.ConfigInfo.TestConfig.TestItems)
            {
                if (testItem != null)
                {
                    if (testItem.IsLimit)
                    {
                        if (testItem.Limit.Upper <= testItem.Limit.Lower)
                        {
                            this.ShowPromptWindow(string.Format("{0}测试项目下限值大于下限值，请重新填写", testItem.Name),PromptType.Red, 1, 0.1);
                            
                        }
                    }
                }
            }

            tb.PreviewMouseDown += new MouseButtonEventHandler(OnPreviewMouseDown);
        }

        private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = e.Source as TextBox;
            tb.SelectAll();
            tb.PreviewMouseDown -= new MouseButtonEventHandler(OnPreviewMouseDown);
        }

        private void tbxLightValueName_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1|| ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                if (ViewModel.NewLightValue < 0)
                {
                    ViewModel.NewLightValue = 0;
                }

                if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 17 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 31)
                {
                    if (ViewModel.NewLightValue > 16383)
                    {
                        ViewModel.NewLightValue = 16383;
                    }
                }
                else
                {
                    if (ViewModel.NewLightValue > 4095)
                    {
                        ViewModel.NewLightValue = 4095;
                    }
                }

            }
            else if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 3)
            {
                if (ViewModel.NewLightValue < 0)
                {
                    ViewModel.NewLightValue = 0;
                }

                if (ViewModel.NewLightValue > 65535)
                {
                    ViewModel.NewLightValue = 65535;
                }
            }
            else
            {
                if (ViewModel.NewLightValue < 0)
                {
                    ViewModel.NewLightValue = 0;
                }

                if (ViewModel.NewLightValue > 128)
                {
                    ViewModel.NewLightValue = 128;
                }

            }
        }

        //单步执行
        #region 单步执行

        private Dictionary<string, object> JsonToDictionary(string jsonData)
        {
            jsonData = jsonData.Trim();
            //实例化JavaScriptSerializer类的新实例
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
                return jss.Deserialize<Dictionary<string, object>>(jsonData);
            }
            catch (Exception ex)
            {
                LogHelper.Info(ex.Message);
                return null;
            }
        }

        private void SingleSetMode()
        {
            if (!_IsSetModelReady)
            {
                #region Model 设置
                AppendTestData("Model设置", MyBrushes.Yellow);
                if (!this._TestStation.DLEDLightingHelper.SetCaseCode(ViewModel.ConfigInfo.TestConfig.TestModelCode < 100 ? ViewModel.ConfigInfo.TestConfig.TestModelCode : int.Parse(ViewModel.ConfigInfo.TestConfig.TestModelCode.ToString().Substring(2))))
                {
                    AppendTestData("Model设置失败", MyBrushes.Red);

                    return;
                }
                else
                {
                    AppendTestData("Model设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
                #endregion

                if (ViewModel.ConfigInfo.TestConfig.IsPwmModeSet)
                {
                    AppendTestData("PWM Mode设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetPWMMode(ViewModel.ConfigInfo.TestConfig.PwnModeCode))
                    {
                        AppendTestData("PWM Mode设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {
                        AppendTestData("PWM Mode设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }
            }
                
            if (ViewModel.ConfigInfo.TestConfig.IsVLedSet)
                {
                    AppendTestData("VLED设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetVBL(ViewModel.ConfigInfo.TestConfig.DvledValue))
                    {
                        AppendTestData("VLED设置失败", MyBrushes.Red);
                        return;
                    }
                    else
                    {
                        AppendTestData("VLED设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }

            if (!_IsSetModelReady)
            {
                if (ViewModel.ConfigInfo.TestConfig.IsOCPOVPSet)
                {
                    AppendTestData("过压过流设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetOCPOVP(ViewModel.ConfigInfo.TestConfig.DvLedOvpValue, ViewModel.ConfigInfo.TestConfig.DvLedOcpValue, ViewModel.ConfigInfo.TestConfig.DICOvpValue, ViewModel.ConfigInfo.TestConfig.DICOcpValue * 1000))
                    {
                        AppendTestData("过压过流设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {
                        AppendTestData("过压过流设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }

                if (ViewModel.ConfigInfo.TestConfig.IsMCSet)
                {
                    AppendTestData("MC设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetMC(ViewModel.ConfigInfo.TestConfig.IMCValue))
                    {
                        AppendTestData("MC设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {

                        AppendTestData("MC设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }

                if (ViewModel.ConfigInfo.TestConfig.IsDCSet)
                {
                    AppendTestData("DC设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetDC(ViewModel.ConfigInfo.TestConfig.IDCValue))
                    {
                        AppendTestData("DC设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {
                        AppendTestData("DC设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }

                if (ViewModel.ConfigInfo.TestConfig.IsBCSet)
                {
                    AppendTestData("BC设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetBC(ViewModel.ConfigInfo.TestConfig.IBCValue))
                    {
                        AppendTestData("BC设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {

                        AppendTestData("BC设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }

                if (ViewModel.ConfigInfo.TestConfig.IsScaleSet)
                {
                    AppendTestData("Scale设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetSCALE(ViewModel.ConfigInfo.TestConfig.IScaleValue))
                    {
                        AppendTestData("Scale设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {

                        AppendTestData("Scale设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }

                if (ViewModel.ConfigInfo.TestConfig.IsILEDSet)
                {
                    AppendTestData("ILED设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetILED(ViewModel.ConfigInfo.TestConfig.IILEDValue))
                    {
                        AppendTestData("ILED设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {

                        AppendTestData("ILED设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }

                if (ViewModel.ConfigInfo.TestConfig.IsSRCSet)
                {
                    AppendTestData("SRC设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetSRC(ViewModel.ConfigInfo.TestConfig.ISrcValue))
                    {
                        AppendTestData("SRC设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {

                        AppendTestData("SRC设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }

                if (ViewModel.ConfigInfo.TestConfig.IsLEDNUMSet)
                {
                    AppendTestData("LEDNUM设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetLEDNUM(ViewModel.ConfigInfo.TestConfig.ILEDNUMValue))
                    {
                        AppendTestData("LEDNUM设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {

                        AppendTestData("LEDNUM设置成功", MyBrushes.Green); 
                        Thread.Sleep(10);
                    }
                }


                if (ViewModel.ConfigInfo.TestConfig.IsRSETSet)
                {
                    AppendTestData("RSET设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetRSET(ViewModel.ConfigInfo.TestConfig.IRSETValue))
                    {
                        AppendTestData("RSET设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {

                        AppendTestData("RSET设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }


                if (ViewModel.ConfigInfo.TestConfig.IsCLKSet)
                {
                    AppendTestData("CLK设置", MyBrushes.Yellow);
                    if (!this._TestStation.DLEDLightingHelper.SetCLK(ViewModel.ConfigInfo.TestConfig.ICLKValue))
                    {
                        AppendTestData("CLK设置失败", MyBrushes.Red);

                        return;
                    }
                    else
                    {

                        AppendTestData("CLK设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }
                }

                
                _IsSetModelReady = true;
            }
           
        }

        private void RecordTestResult(string resultData,string testName)
        {
            Dictionary<string, object> DicResult = JsonToDictionary(resultData);

            if (DicResult != null)
            {
                foreach (var d in DicResult)
                {
                    if (d.Key == "CMD")
                    {
                        AppendTestData(testName, MyBrushes.RichBlue);
                    }
                    else
                    {
                        AppendTestData(string.Format("{0}:{1}", d.Key, d.Value), MyBrushes.TESTING);
                    }
                }
            }
            else
            {
                this.ShowPromptWindow("返回数据失败，请重试", PromptType.Red);
            }

        }

        private void btnSingleExecuteCmd_OnClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;

            if (button != null)
            {
                this.rtxtTestData.Document.Blocks.Clear();

                string testItemCode = (string)button.Tag;

                TestItem testItem = ViewModel.ConfigInfo.TestConfig.TestItems.First(s=>s.TestItemCode== testItemCode);

                string Result = "";


                Task.Factory.StartNew(() =>
                {
                    this.Loading.Show("Testing...");

                    SingleSetMode();

                    #region Pin短路开路测试
                    if (testItem.TestItemCode == "PINShortOpenTest")
                    {

                        Result = this._TestStation.DLEDLightingHelper.GetPinOSTestData();

                        RecordTestResult(Result, testItem.Name);

                        //AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    else
                    {
                        Result = this._TestStation.DLEDLightingHelper.GetPinOSTestData();

                        RecordTestResult(Result, "Pin短路开路测试");

                        //AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);
                    }
                    #endregion

                    #region NTC极性测试
                    if (testItem.TestItemCode == "DiodePolarityTest")
                    {
                        Result = this._TestStation.DLEDLightingHelper.GetDiodePolarity();

                        RecordTestResult(Result, testItem.Name);

                        //AppendTestData(string.Format("{0}-测试结果：{1}", testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;

                    }
                    #endregion

                    #region 常温下热敏电阻测试
                    if (testItem.TestItemCode == "ThermistorTestingRoomTemperature")
                    {
                        Result = this._TestStation.DLEDLightingHelper.GetNTCData();

                        RecordTestResult(Result, testItem.Name);

                        // AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    #endregion

                    #region 芯片待机电流
                    if (testItem.TestItemCode == "ChipStandbyCurrent")
                    {
                        Result = this._TestStation.DLEDLightingHelper.GetLEDDriverICStandbyVolCurData();

                        RecordTestResult(Result, testItem.Name);

                        //AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    else
                    {
                        Result = this._TestStation.DLEDLightingHelper.GetLEDDriverICStandbyVolCurData();

                        RecordTestResult(Result, "芯片待机电流测试");

                        // AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);
                    }
                    #endregion

                    #region IFBDataTest
                    if (testItem.TestItemCode == "IFBDataTest")
                    {
                        Result = this._TestStation.DLEDLightingHelper.GetIFBData();

                        RecordTestResult(Result, testItem.Name);

                        // AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    #endregion

                    #region 芯片正常运行电流
                    if (testItem.TestItemCode == "ChipWorkingCurrent")
                    {
                        Result = this._TestStation.DLEDLightingHelper.GetLEDDriverICWorkingVolCurData();

                        RecordTestResult(Result, testItem.Name);

                        // AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    else
                    {
                        Result = this._TestStation.DLEDLightingHelper.GetLEDDriverICWorkingVolCurData();

                        RecordTestResult(Result, "芯片正常运行电流");

                        // AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);
                    }
                    #endregion

                    #region VLED亮度全关的漏电流
                    if (testItem.TestItemCode == "VLEDFullyClosedCurrent")
                    {

                        this.SetMCDCBCScaleForTestItem(testItem);

                        Result = this._TestStation.DLEDLightingHelper.GetAllLEDTestData(testItem.SetCurrentValue);

                        RecordTestResult(Result, testItem.Name);

                        //AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    #endregion

                    #region 单路LED低、高电流
                    if (testItem.TestItemCode == "SingleLEDLowCurrent" || testItem.TestItemCode == "SingleLEDHighCurrent")
                    {
                        this.SetMCDCBCScaleForTestItem(testItem);

                        Result = this._TestStation.DLEDLightingHelper.GetSingleLEDTestData(testItem.SetCurrentValue);

                        RecordTestResult(Result, testItem.Name);

                        // AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    #endregion

                    #region LED单芯片回路低、高电流
                    if (testItem.TestItemCode == "LEDSingleICLowCurrent" || testItem.TestItemCode == "LEDSingleICHighCurrent")
                    {
                        this.SetMCDCBCScaleForTestItem(testItem);

                        Result = this._TestStation.DLEDLightingHelper.GetICLEDTestData(testItem.SetCurrentValue);

                        RecordTestResult(Result, testItem.Name);

                        //AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    #endregion

                    #region 全画面低、高电流
                    if (testItem.TestItemCode == "FullScreenLowCurrent" || testItem.TestItemCode == "FullScreenHighCurrent")
                    {
                        this.SetMCDCBCScaleForTestItem(testItem);

                        Result = this._TestStation.DLEDLightingHelper.GetAllLEDTestData(testItem.SetCurrentValue);

                        RecordTestResult(Result, testItem.Name);
                        // AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    #endregion

                    #region 点灯后热敏电阻测试
                    if (testItem.TestItemCode == "ThermistorTestingLightingTemperature")
                    {
                        this.SetMCDCBCScale();

                        Result = this._TestStation.DLEDLightingHelper.GetNTCData();

                        RecordTestResult(Result, testItem.Name);
                        //AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    #endregion

                    #region 棋盘LED
                    if (testItem.TestItemCode == "QiPanPattenDisplay")
                    {
                        #region 棋盘指令方式
                        //if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 11)
                        //{
                        //    SetMC(ViewModel.ConfigInfo.TestConfig.CheckerBoardSetMC);

                        //    string Led = ViewModel.ConfigInfo.TestConfig.CheckerBoardIC1 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC2 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC3 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC4 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC5 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC6 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC7 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC8 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC9 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC10 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC11 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC12 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC13 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC14 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC15 + " " +
                        //                 ViewModel.ConfigInfo.TestConfig.CheckerBoardIC16;
                        //    this._TestStation.DLEDLightingHelper.SetCheckerBoardPictureData("0 ", Led);


                        //    Result = this._TestStation.DLEDLightingHelper.ShowCheckerBoardPicture(ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue);

                        //    RecordTestResult(Result, testItem.Name);

                        //    Thread.Sleep(ViewModel.ConfigInfo.TestConfig.DIYPictureDelayTimeMs);
                        //}
                        //else
                        //{
                            #endregion

                        if (ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList.Count > 0)
                        {
                            this.SetMCDCBCScaleForDIY();

                            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 6 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4)
                            {
                                
                                foreach (RootDIYLedModel rootDIYLedModel in ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList)
                                {
                                    if (rootDIYLedModel.IsTest)
                                    {
                                        AppendTestData(string.Format("棋盘格 图案：{0}", rootDIYLedModel.RootName), MyBrushes.Green);
                                        //排序
                                        List<IGrouping<string, DIYLedModel>> dIYLedModelICGroup = rootDIYLedModel.DiyLedModelList.GroupBy(t => t.ICID).ToList();

                                        foreach (IGrouping<string, DIYLedModel> ICGroup in dIYLedModelICGroup)
                                        {
                                            string IC = ICGroup.Key;

                                            List<IGrouping<string, DIYLedModel>> dIYLedModelScanNumGroup = ICGroup.GroupBy(t => t.Scan_num).ToList();

                                            foreach (IGrouping<string, DIYLedModel> ScanNumGroup in dIYLedModelScanNumGroup)
                                            {
                                                string ScanNum = ScanNumGroup.Key;

                                                List<DIYLedModel> dIYLedModels = ScanNumGroup.OrderBy(a => a.LEDID).ToList();

                                                int foregroundLight = 0;
                                                int backgroundLight = 0;

                                                int LedCount = ViewModel.ConfigInfo.TestConfig.IC_PinCount;

                                                string LedData = "";

                                                for (int indexLed = 1; indexLed < LedCount + 1; indexLed++)
                                                {
                                                    DIYLedModel dIYLedModel = dIYLedModels.FirstOrDefault(s => s.LEDID == indexLed);

                                                    if (dIYLedModel == null)
                                                    {
                                                        LedData += " " + backgroundLight.ToString();
                                                    }
                                                    else
                                                    {
                                                        foregroundLight = dIYLedModel.LightValue;

                                                        if (dIYLedModel.IsFlag == Visibility.Visible)
                                                        {
                                                            if (dIYLedModel.LedType == "Nomal")
                                                            {
                                                                LedData += " " + foregroundLight.ToString();
                                                            }
                                                            else
                                                            {
                                                                LedData += " " + foregroundLight.ToString();
                                                            }
                                                        }
                                                    }
                                                }

                                                this._TestStation.DLEDLightingHelper.SetDIYPictureData(IC, ScanNum, LedData);
                                            }

                                        }

                                        Result = this._TestStation.DLEDLightingHelper.showDIYPicture(0);

                                        RecordTestResult(Result, testItem.Name);

                                        Thread.Sleep(ViewModel.ConfigInfo.TestConfig.DIYPictureDelayTimeMs);
                                    }

                                }

                            }
                            else
                            {
                                foreach (RootDIYLedModel rootDIYLedModel in ViewModel.ConfigInfo.TestConfig.RootQiPanLedModelList)
                                {
                                    if (rootDIYLedModel.IsTest)
                                    {
                                        //AppendTestData(string.Format("棋盘格 图案：{0}", rootDIYLedModel.RootName), MyBrushes.Green);
                                        //排序
                                        List<IGrouping<string, DIYLedModel>> dIYLedModelGroup = rootDIYLedModel.DiyLedModelList.GroupBy(t => t.ICID).ToList();

                                        foreach (IGrouping<string, DIYLedModel> group in dIYLedModelGroup)
                                        {
                                            string IC = group.Key;

                                            string Led = "";

                                            int i = 0;

                                            List<DIYLedModel> dIYLedModels = group.OrderBy(a => a.LEDID).ToList();

                                            int foregroundLight = 0;
                                            int backgroundLight = 0;

                                            int LedCount = ViewModel.ConfigInfo.TestConfig.IC_PinCount;

                                            //if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 1 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 8 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 9 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 11)
                                            //{
                                            //    //backgroundLight = 0;
                                            //    LedCount = 16;
                                            //}
                                            //else
                                            //{
                                            //    //backgroundLight = 128;
                                            //    LedCount = 48;
                                            //}

                                            for (int indexLed = 1; indexLed < LedCount + 1; indexLed++)
                                            {
                                                DIYLedModel dIYLedModel = dIYLedModels.FirstOrDefault(s => s.LEDID == indexLed);

                                                if (dIYLedModel == null)
                                                {
                                                    Led += " " + backgroundLight.ToString();
                                                }
                                                else
                                                {
                                                    foregroundLight = dIYLedModel.LightValue;

                                                    if (dIYLedModel.IsFlag == Visibility.Visible)
                                                    {
                                                        if (dIYLedModel.LedType == "Nomal")
                                                        {
                                                            Led += " " + foregroundLight.ToString();
                                                        }
                                                        else
                                                        {
                                                            Led += " " + foregroundLight.ToString();
                                                        }
                                                    }
                                                }
                                            }
                                            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
                                            {

                                                this._TestStation.DLEDLightingHelper.SetDIYPictureData(IC, Led);
                                            }
                                            else
                                            {
                                                this._TestStation.DLEDLightingHelper.SetCheckerBoardPictureData(IC, Led);
                                            }
                                        }

                                        if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
                                        {
                                            Result = this._TestStation.DLEDLightingHelper.showDIYPicture(0);
                                        }
                                        else
                                        {
                                            Result = this._TestStation.DLEDLightingHelper.ShowCheckerBoardPicture(ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue);
                                        }

                                        RecordTestResult(Result, testItem.Name);
                                        //AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                                        Thread.Sleep(ViewModel.ConfigInfo.TestConfig.DIYPictureDelayTimeMs);
                                    }

                                }
                            }
                        }
                        else
                        {
                            Result = "0";
                        }
                    }
                    #endregion

                    #region DIYLED
                    if (testItem.TestItemCode == "DIYPattenDisplay")
                    {
                        if (ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList.Count > 0)
                        {
                            this.SetMCDCBCScaleForDIY();

                            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 6 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4)
                            {
                                
                                foreach (RootDIYLedModel rootDIYLedModel in ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList)
                                {
                                    if (rootDIYLedModel.IsTest)
                                    {

                                        AppendTestData(string.Format("DIY 图案：{0}", rootDIYLedModel.RootName), MyBrushes.Green);
                                        //排序
                                        List<IGrouping<string, DIYLedModel>> dIYLedModelICGroup = rootDIYLedModel.DiyLedModelList.GroupBy(t => t.ICID).ToList();

                                        foreach (IGrouping<string, DIYLedModel> ICGroup in dIYLedModelICGroup)
                                        {
                                            string IC = ICGroup.Key;

                                            List<IGrouping<string, DIYLedModel>> dIYLedModelScanNumGroup = ICGroup.GroupBy(t => t.Scan_num).ToList();

                                            foreach (IGrouping<string, DIYLedModel> ScanNumGroup in dIYLedModelScanNumGroup)
                                            {
                                                string ScanNum = ScanNumGroup.Key;

                                                List<DIYLedModel> dIYLedModels = ScanNumGroup.OrderBy(a => a.LEDID).ToList();

                                                int foregroundLight = 0;
                                                int backgroundLight = 0;

                                                int LedCount = ViewModel.ConfigInfo.TestConfig.IC_PinCount;

                                                string LedData = "";

                                                for (int indexLed = 1; indexLed < LedCount + 1; indexLed++)
                                                {
                                                    DIYLedModel dIYLedModel = dIYLedModels.FirstOrDefault(s => s.LEDID == indexLed);

                                                    if (dIYLedModel == null)
                                                    {
                                                        LedData += " " + backgroundLight.ToString();
                                                    }
                                                    else
                                                    {
                                                        foregroundLight = dIYLedModel.LightValue;

                                                        if (dIYLedModel.IsFlag == Visibility.Visible)
                                                        {
                                                            if (dIYLedModel.LedType == "Nomal")
                                                            {
                                                                LedData += " " + foregroundLight.ToString();
                                                            }
                                                            else
                                                            {
                                                                LedData += " " + foregroundLight.ToString();
                                                            }
                                                        }
                                                    }
                                                }

                                                this._TestStation.DLEDLightingHelper.SetDIYPictureData(IC, ScanNum, LedData);
                                            }

                                        }

                                        this._TestStation.DLEDLightingHelper.showDIYPicture(0);

                                        RecordTestResult(Result, testItem.Name);

                                        Thread.Sleep(ViewModel.ConfigInfo.TestConfig.DIYPictureDelayTimeMs);
                                    }

                                }

                            }

                            else
                            {
                                foreach (RootDIYLedModel rootDIYLedModel in ViewModel.ConfigInfo.TestConfig.RootDiyLedModelList)
                                {
                                    if (rootDIYLedModel.IsTest)
                                    {
                                        AppendTestData(string.Format("DIY 图案：{0}", rootDIYLedModel.RootName), MyBrushes.Green);
                                        //排序
                                        List<IGrouping<string, DIYLedModel>> dIYLedModelGroup = rootDIYLedModel.DiyLedModelList.GroupBy(t => t.ICID).ToList();

                                        foreach (IGrouping<string, DIYLedModel> group in dIYLedModelGroup)
                                        {

                                            string IC = group.Key;

                                            string Led = "";

                                            int i = 0;

                                            List<DIYLedModel> dIYLedModels = group.OrderBy(a => a.LEDID).ToList();

                                            int foregroundLight = 0;
                                            int backgroundLight = 0;

                                            int LedCount = ViewModel.ConfigInfo.TestConfig.IC_PinCount;

                                            //if (ViewModel.ConfigInfo.TestConfig.TestModelCode == 1 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 8 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 9 || ViewModel.ConfigInfo.TestConfig.TestModelCode == 11)
                                            //{
                                            //    LedCount = 16;
                                            //}
                                            //else
                                            //{
                                            //    LedCount = 48;
                                            //}

                                            for (int indexLed = 1; indexLed < LedCount + 1; indexLed++)
                                            {
                                                DIYLedModel dIYLedModel = dIYLedModels.FirstOrDefault(s => s.LEDID == indexLed);

                                                if (dIYLedModel == null)
                                                {
                                                    Led += " " + backgroundLight.ToString();
                                                }
                                                else
                                                {
                                                    foregroundLight = dIYLedModel.LightValue;

                                                    if (dIYLedModel.IsFlag == Visibility.Visible)
                                                    {
                                                        if (dIYLedModel.LedType == "Nomal")
                                                        {
                                                            Led += " " + foregroundLight.ToString();
                                                        }
                                                        else
                                                        {
                                                            Led += " " + foregroundLight.ToString();//backgroundLight.ToString();
                                                        }
                                                    }
                                                }
                                            }


                                            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
                                            {
                                                this._TestStation.DLEDLightingHelper.SetDIYPictureData(IC, Led);

                                            }
                                            else
                                            {
                                                this._TestStation.DLEDLightingHelper.SetCheckerBoardPictureData(IC, Led);
                                            }
                                        }

                                        if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 3 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
                                        {
                                            Result = this._TestStation.DLEDLightingHelper.showDIYPicture(0);
                                        }
                                        else
                                        {
                                            Result = this._TestStation.DLEDLightingHelper.ShowCheckerBoardPicture(ViewModel.ConfigInfo.TestConfig.DIYPictureSetValue);

                                        }

                                        RecordTestResult(Result, testItem.Name);
                                        // AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                                        Thread.Sleep(ViewModel.ConfigInfo.TestConfig.DIYPictureDelayTimeMs);
                                    }

                                }

                            }
                        }
                        else
                        {
                            Result = "";
                        }
                    }
                    #endregion

                    #region 10uA电流测试
                    if (testItem.TestItemCode == "CurrentTest10uA")
                    {
                        this.SetMCDCBCScale();


                        Result = this._TestStation.DLEDLightingHelper.GetUATestData();

                        RecordTestResult(Result, testItem.Name);
                        // AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    #endregion

                    #region 全电流测试
                    if (testItem.TestItemCode == "FullCurrentTest1" || testItem.TestItemCode == "FullCurrentTest2" || testItem.TestItemCode == "FullCurrentTest3" || testItem.TestItemCode == "FullCurrentTest4" || testItem.TestItemCode == "FullCurrentTest5" || testItem.TestItemCode == "FullCurrentTest6")
                    {
                        this.SetMCDCBCScaleForTestItem(testItem);

                        Result = this._TestStation.DLEDLightingHelper.GetAllLEDTestData(testItem.SetCurrentValue);

                        RecordTestResult(Result, testItem.Name);
                        // AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                        return;
                    }
                    #endregion

                    #region ESD测试
                    if (testItem.TestItemCode == "ESDTest")
                    {
                        Result = this._TestStation.DLEDLightingHelper.GetESDTestData((int)testItem.SetCurrentValue);

                        RecordTestResult(Result, testItem.Name);
                        //AppendTestData(string.Format("{0}-测试结果：{1}",testItem.Name, Result), MyBrushes.TESTING);

                        Thread.Sleep(testItem.DelayTime);

                    }
                    #endregion

                }).ContinueWith(t =>
                {

                    Thread.Sleep(500);

                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        if(cbAutoPowerOffName.IsChecked == true)
                        {
                            AppendTestData("关闭电源", MyBrushes.Green);

                            this._TestStation.DLEDLightingHelper.PowerOff();

                            AppendTestData("结束测试", MyBrushes.Green);

                        }

                    }));

                    this.Loading.Hide();

                });
            }


        }
        #endregion

        #region SETMCDCBC
        private void SetMCDCBCScaleForTestItem(TestItem testItem)
        {
            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                SetMC(testItem);
            }
            else if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 3)
            {
                SetSCALE_ILED(testItem);
            }
            else
            {
                SetMCDCBC(testItem);

            }
        }

        private bool SetMCDCBC(TestItem testItemResult)
        {
            bool isSuccess = true;

            AppendTestData("MC设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetMC(testItemResult.SetMcValue))
            {
                AppendTestData("MC设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("MC设置成功", MyBrushes.Green);
            }

            AppendTestData("DC设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetDC(testItemResult.SetDcValue))
            {
                AppendTestData("DC设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("DC设置成功", MyBrushes.Green);
            }

            AppendTestData("BC设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetBC(testItemResult.SetBcValue))
            {
                AppendTestData("BC设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("BC设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }

        private bool SetMC(TestItem testItemResult)
        {
            bool isSuccess = true;

            AppendTestData("MC设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetMC(testItemResult.SetMcValue))
            {
                AppendTestData("MC设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("MC设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }

        private bool SetSCALE_ILED(TestItem testItemResult)
        {
            bool isSuccess = true;

            AppendTestData("Scale设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetSCALE(testItemResult.SetScaleValue))
            {
                AppendTestData("Scale设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("Scale设置成功", MyBrushes.Green);
            }

            AppendTestData("ILED设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetILED(testItemResult.SetILedValue))
            {
                AppendTestData("ILED设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("ILED设置成功", MyBrushes.Green);
            }
            return isSuccess;
        }


        private void SetMCDCBCScale()
        {
            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                SetMC(ViewModel.ConfigInfo.TestConfig.IMCValue);

            }
            else if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 3)
            {
                SetSCALE_ILED(ViewModel.ConfigInfo.TestConfig.IScaleValue, ViewModel.ConfigInfo.TestConfig.IILEDValue);
            }
            else
            {
                SetMCDCBC(ViewModel.ConfigInfo.TestConfig.IMCValue, ViewModel.ConfigInfo.TestConfig.IDCValue, ViewModel.ConfigInfo.TestConfig.IBCValue);
            }

        }

        private void SetMCDCBCScaleForDIY()
        {
            if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 1 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 4 || ViewModel.ConfigInfo.TestConfig.TestCaseType == 5)
            {
                SetMC(ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC);
            }
            else if (ViewModel.ConfigInfo.TestConfig.TestCaseType == 3)
            {
                SetSCALE_ILED(ViewModel.ConfigInfo.TestConfig.DIYPictureSetScale, ViewModel.ConfigInfo.TestConfig.DIYPictureSetILED);
            }
            else
            {
                SetMCBC(ViewModel.ConfigInfo.TestConfig.DIYPictureSetMC, ViewModel.ConfigInfo.TestConfig.DIYPictureSetBC);

            }

        }
        private bool SetSCALE_ILED(int ScaleValue, int ILEDValue)
        {
            bool isSuccess = true;

            AppendTestData("Scale设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetSCALE(ScaleValue))
            {
                AppendTestData("Scale设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("Scale设置成功", MyBrushes.Green);
            }

            AppendTestData("ILED设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetILED(ILEDValue))
            {
                AppendTestData("ILED设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("ILED设置成功", MyBrushes.Green);
            }
            return isSuccess;
        }
        private bool SetMCDCBC(int MCValue, int DCValue, int BCValue)
        {
            bool isSuccess = true;

            AppendTestData("MC设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetMC(MCValue))
            {
                AppendTestData("MC设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("MC设置成功", MyBrushes.Green);
            }

            AppendTestData("DC设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetDC(DCValue))
            {
                AppendTestData("DC设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("DC设置成功", MyBrushes.Green);
            }

            AppendTestData("BC设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetBC(BCValue))
            {
                AppendTestData("BC设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("BC设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }
        private bool SetMCBC(int MCValue, int BCValue)
        {
            bool isSuccess = true;

            AppendTestData("MC设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetMC(MCValue))
            {
                AppendTestData("MC设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("MC设置成功", MyBrushes.Green);
            }

            AppendTestData("BC设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetBC(BCValue))
            {
                AppendTestData("BC设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("BC设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }

        private bool SetMC(int MCValue)
        {
            bool isSuccess = true;

            AppendTestData("MC设置", MyBrushes.Yellow);
            if (!this._TestStation.DLEDLightingHelper.SetMC(MCValue))
            {
                AppendTestData("MC设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("MC设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }

        #endregion

        #region 追加测试信息
        private Block AppendTestData(string data, MyBrushes statusBrush)
        {
            Block block = null;

            if (this.Dispatcher.Thread == System.Threading.Thread.CurrentThread)
            {
                block = GetBlock(data, statusBrush);

                this.rtxtTestData.Document.Blocks.Add(block);
            }
            else
            {
                this.Dispatcher.Invoke((Action)delegate
                {
                    block = AppendTestData(data, statusBrush);
                });
            }

            return block;
        }

        private Block GetBlock(string data, MyBrushes statusBrush)
        {
            Inline inline = new Run(data);

            inline.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(statusBrush.ToBrushString()));

            return new Paragraph(inline) { LineHeight = 1.0 };
        }

        private void rtxtTestData_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.rtxtTestData.ScrollToEnd();
        }

        #endregion
        
    }
}
